コア DOM のパブリック プロパティとメソッド
コア DOM のパブリック プロパティとメソッド
注: コア DOM 內(nèi)のノード (マーカー) の検索は、ルート ノード (HTML ノード) から始まります。
ノードアクセス
nodeName: ノード名。
nodeValue: ノードの値。テキスト ノードのみが値を持ち、要素ノードには値がありません。 nodeValue の値は「プレーン テキスト」のみにすることができ、HTML タグや CSS 屬性を含めることはできません。
firstChild: 1 番目の子ノード。
lastChild: 最後の子ノード。
childNodes: 子ノードのリスト。配列です。
parentNode: 親ノード。
タグの検索方法
document.firstChild
document.firstChild.lastChild
document.body
ノードの屬性 操作
setAttribute(name, value): ノードに屬性を追加します。
getAttribute(name): ノード屬性の値を取得します。
removeAttribute(name): ノードの屬性を削除します。
<!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é)點(diǎn) var node_body = document.all.div1; //查找img節(jié)點(diǎn) 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>
ノードの作成
document.createElement(tagName): 指定されたHTMLタグ、ノードを作成します
-
tagName: HTML タグ名なしを意味します山かっこ內(nèi)。
例: var imgObj = document.createElement("img")
parentNode.appendChild(childNode): 作成したノードを親ノードに追加します。
parentNode は親ノードを表し、親ノードは存在する必要があります。
childNode は子ノードを表します。
例: document.body.appendChild(imgObj)
parentNode.removeChild(childNode): 親ノードの下にある子ノードを削除します。
parentNode は親ノードを表します。
childNode は、削除される子ノードを表します。
例: document.body.removeChild(imgObj)
<!DOCTYPE HTML> <html> <head> <meta charset="utf-8" /> <title>php.cn</title> <script > //網(wǎng)頁(yè)加載完成后 window.onload = function(){ //創(chuàng)建一個(gè)<img>標(biāo)記 var imgObj = document.createElement("img"); //增加屬性 imgObj.setAttribute("src","/upload/course/000/000/009/580ae23c4a88a881.jpg"); imgObj.setAttribute("width","400"); //將創(chuàng)建的圖片節(jié)點(diǎn),掛載到某個(gè)父節(jié)點(diǎn)下 document.body.appendChild(imgObj); } </script> </head> <body> </body> </html>