コア DOM のパブリック プ...ログイン

コア DOM のパブリック プロパティとメソッド

コア DOM のパブリック プロパティとメソッド

注: コア DOM 内のノード (マーカー) の検索は、ルート ノード (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节点
 var node_body = document.all.div1;
 //查找img节点
 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 タグ名なしを意味します山かっこ内。

  • 例: 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 >
//网页加载完成后
window.onload = function(){
    //创建一个<img>标记
    var imgObj = document.createElement("img");
    //增加属性
    imgObj.setAttribute("src","/upload/course/000/000/009/580ae23c4a88a881.jpg");
    imgObj.setAttribute("width","400");
    //将创建的图片节点,挂载到某个父节点下
    document.body.appendChild(imgObj);
}
</script>
</head>
<body>
</body>
</html>
次のセクション
<!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节点 var node_body = document.all.div1; //查找img节点 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>
コースウェア