核心DOM中的公共的屬性和方法
核心DOM中的公共的屬性和方法
注:核心DOM中查找節(jié)點(標記),都是從根節(jié)點開始的(html節(jié)點)。
節(jié)點訪問
nodeName:節(jié)點名稱。
nodeValue:節(jié)點的值。只有文本節(jié)點才有值,元素節(jié)點沒有值。nodeValue的值只能是“純文本”,不能含有任何的HTML標記或CSS屬性。
firstChild:第1個子節(jié)點。
lastChild:最后1個子節(jié)點。
childNodes:子節(jié)點列表,是一個數(shù)組。
parentNode:父節(jié)點。
查找標記的方法
document.firstChild
document.firstChild.lastChild
document.body
對節(jié)點的屬性操作
setAttribute(name,value):給某個節(jié)點添加一個屬性。
getAttribute(name):獲取某個節(jié)點屬性的值。
removeAttribute(name):刪除某個節(jié)點的屬性。
<!DOCTYPE HTML> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8"> <title>php.cn</title> <script type="text/javascript"> window.onload = function(){ //查找body節(jié)點 var node_body = document.all.div1; //查找img節(jié)點 var imgObj = node_body.firstChild; //增加屬性 imgObj.setAttribute("src","https://img.php.cn/upload/course/000/000/009/580ae23c4a88a881.jpg"); imgObj.setAttribute("width","400"); imgObj.setAttribute("border","2"); imgObj.setAttribute("style","cursor:pointer;"); //刪除border屬性 imgObj.removeAttribute("border"); } </script> </head> <body ><div id="div1"><img /></div></body> </html>
節(jié)點的創(chuàng)建
document.createElement(tagName):創(chuàng)建一個指定的HTML標記,一個節(jié)點
tagName:是指不帶尖括號的HTML標記名稱。
舉例:var imgObj = document.createElement(“img”)
parentNode.appendChild(childNode):將創(chuàng)建的節(jié)點,追加到某個父節(jié)點下。
parentNode代表父節(jié)點,父節(jié)點必須存在。
childNode代表子節(jié)點。
舉例:document.body.appendChild(imgObj)
parentNode.removeChild(childNode):刪除某個父節(jié)點下的子節(jié)點。
parentNode代表父節(jié)點。
childNode代表要刪除的子節(jié)點。
舉例:document.body.removeChild(imgObj)
<!DOCTYPE HTML> <html> <head> <meta charset="utf-8" /> <title>php.cn</title> <script > //網(wǎng)頁加載完成后 window.onload = function(){ //創(chuàng)建一個<img>標記 var imgObj = document.createElement("img"); //增加屬性 imgObj.setAttribute("src","/upload/course/000/000/009/580ae23c4a88a881.jpg"); imgObj.setAttribute("width","400"); //將創(chuàng)建的圖片節(jié)點,掛載到某個父節(jié)點下 document.body.appendChild(imgObj); } </script> </head> <body> </body> </html>