js添加頁面元素


js動態創建html元素需要使用到下面這些常見的js方法。
getElementById();//返回帶有指定 ID 的元素。
getElementsByTagName();//返回包含帶有指定標簽名稱的所有元素的節點列表(集合/節點數組)。
getElementsByClassName();//返回包含帶有指定類名的所有元素的節點列表。
appendChild();//把新的子節點添加到指定節點。
removeChild();//刪除子節點。
replaceChild();//替換子節點。
insertBefore();//在指定的子節點前面插入新的子節點。
createAttribute();//創建屬性節點。
createElement();//創建元素節點。
createTextNode();//創建文本節點。
getAttribute(); //返回指定的屬性值。
setAttribute(); //把指定屬性設置或修改為指定的值。

下面的示例代碼在id為parent_div的div內部創建id為child_div的div,再在child_div內部創建id為r_id的radio,並使其被選中。

var newdiv=document.createElement("div"); newdiv.id="child_div"; document.getElementById("parent_div").appendChild(newdiv); var radio= document.createElement("input"); radio.setAttribute("type","checkbox"); radio.setAttribute("name","r_name"); radio.setAttribute("id",'r_id'); document.getElementById('child_div').appendChild(radio); document.getElementById('child_div').appendChild(document.createTextNode("選擇我")); radio.setAttribute("checked",'checked');


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM