美文网首页
《Javacript DOM 编程艺术》笔记(二)The Doc

《Javacript DOM 编程艺术》笔记(二)The Doc

作者: 红烧排骨饭 | 来源:发表于2018-05-26 22:18 被阅读0次

    The Document Object Model

    • The concept of nodes;
    • Five very handly DOM methods: getElementById, getElementByTagName, getElementsByClassName, getAttribute and setAttribute

    D is for document

    HTML 就是 Document 的表现形式

    Object of desire

    各种各样的对象,比如

    • window
    • document

    Dia M for model

    标签树

    Nodes

    • Element nodes
    • Text nodes
    • Attribute nodes

    举个例子

    <p title="a gentle reminder">Don't forget to buy this stuff.</p>
    

    Element nodes 是: <p></p>
    Text nodesDon't forget to buy this stuff.
    Attribute nodestitle="a gentle reminder"

    Getting Elements

    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="utf-8" />
        <title>Shopping list</title>
    </head>
    <body>
        <h1>What to buy</h1>
        <p title="a gentle reminder">Don't forget to buy this stuff.</p>
        <ul id="purchases">
            <li>A tin of beans</li>
            <li class="sale">Cheese</li>
            <li class="sale important">Milk</li>
        </ul>
        <script>
            alert(typeof document.getElementById("purchases"));
        </script>
    </body>
    </html>
    
    • document.getElementById("purchases")
    • document.getElementsByTagName("li")
    • document.getElementsByClassName("sale")

    Getting and Setting Attributes

    getAttribute

    var paras = document.getElementsByTagName("p");
    for (var i=0; i < paras.length; i++ ) {
        console.log(paras[i].getAttribute("title"));
    }
    

    setAttribute

    var paras = document.getElementsByTagName("p");
    for (var i=0; i< paras.length; i++) {
        var title_text = paras[i].getAttribute("title");
        if (title_text) {
            paras[i].setAttribute("title","brand new title text");
            console.log(paras[i].getAttribute("title"));
        }
    }
    

    相关文章

      网友评论

          本文标题:《Javacript DOM 编程艺术》笔记(二)The Doc

          本文链接:https://www.haomeiwen.com/subject/pqjvjftx.html