HTML DOM 属性方法使用详情(1)

(ps:个人学习记录笔记)

DOM 是将 HTML 内容表达为树结构。

HTML DOM Node Tree

    HTML DOM是中立于平台和语言的接口,它允许程序和脚本动态地访问和更新文档的内容、结构和样式。在 HTML DOM 中,所有事物都是节点。DOM 是被视为节点树的 HTML。通过 HTML DOM,树中的所有节点均可通过 JavaScript 进行访问。所有 HTML 元素(节点)均可被修改,也可以创建或删除节点。

    节点树中的节点彼此拥有层级关系。父(parent)、子(child)和同胞(sibling)等术语用于描述这些关系。父节点拥有子节点。同级的子节点被称为同胞(兄弟或姐妹)。



http://www.w3school.com.cn/i/dom_navigate.gif

常用DOM对象方法:

方法
描述
getElementById() 返回带有指定 ID 的元素。
getElementsByTagName() 返回包含带有指定标签名称的所有元素的节点列表(集合/节点数组)。
getElementsByClassName() 返回包含带有指定类名的所有元素的节点列表。
appendChild() 把新的子节点添加到指定节点。
removeChild() 删除子节点。
replaceChild() 替换子节点。
insertBefore() 在指定的子节点前面插入新的子节点。
createAttribute() 创建属性节点。
createElement() 创建元素节点。
createTextNode() 创建文本节点。
getAttribute() 返回指定的属性值。
setAttribute()

把指定属性设置或修改为指定的值。

  1. getElementById() 方法

    getElementById() 方法返回带有指定 ID 的元素:

    <!DOCTYPE html>
    <html>
        <body>
            <p id="hello">Hello World!</p>
            <p>实现 <b>getElementById</b> 方法</p>
            <script>
             x=document.getElementById("hello");
            document.write("<p>hello的文本内容是:" + x.innerHTML + "</p>");
            </script>
    
        </body>
    </html>

2.getElementsByTagName() 方法

getElementsByTagName() 返回带有指定标签名的所有元素。


<!DOCTYPE html>
<html>
    <body>

        <p>Hello World!</p>
        <p>China No.1 !!!</p>
        <p>实现 <b>getElementsByTagName</b> 方法</p>

        <script>
            x=document.getElementsByTagName("p");
            document.write("第一行的文本内容是: " + x[0].innerHTML);
        </script>

    </body>
</html>

3.getElementsByClassName() 方法

getElementsByClassName() 方法是查找带有相同类名的所有 HTML 元素:

 
 
<!DOCTYPE html>
<html>
    <body>

        <p class="test">Hello World!</p>
        <p class="test">China No.1 !!!</p>
        <p class="test">实现 <b>getElementsByTagName</b> 方法</p>

        <script>
            document.getElementsByClassName("test");
            document.write(document.getElementsByClassName("test");
        </script>

    </body>
</html>

猜你喜欢

转载自blog.csdn.net/baidu_40297578/article/details/80549886