http://www.imooc.com/code/1696
創建元素節點createElement
createElement()方法可創建元素節點。此方法可返回一個 Element 對象。
語法:
document.createElement(tagName)
參數:
tagName:字符串值,這個字符串用來指明創建元素的類型。
注意:要與appendChild() 或 insertBefore()方法聯合使用,將元素顯示在頁面中。
我們來創建一個按鈕,代碼如下:
<script type="text/javascript"> var body = document.body; var input = document.createElement("input"); input.type = "button"; input.value = "創建一個按鈕"; body.appendChild(input); </script>
效果:在HTML文檔中,創建一個按鈕。
我們也可以使用setAttribute來設置屬性,代碼如下:
<script type="text/javascript"> var body= document.body; var btn = document.createElement("input"); btn.setAttribute("type", "text"); btn.setAttribute("name", "q"); btn.setAttribute("value", "使用setAttribute"); btn.setAttribute("onclick", "javascript:alert('This is a text!');"); body.appendChild(btn); </script>
效果:在HTML文檔中,創建一個文本框,使用setAttribute設置屬性值。 當點擊這個文本框時,會彈出對話框“This is a text!”。