DOM access to page elements

Position page elements

How to locate page elements

The Document object provides attributes and methods to realize the function of locating page elements, which is also one of the main applications of the Docu ument object in the DOM standard specification.

The Document object provides methods for positioning page elements as follows:

● getElementByld()方法:  通过页面元素的id属性值定位元素。.

● getElementsByName()方法:  通过页面元素的name属性值定位元素。

● getElementsByTagName()方法: 通过页面元素的元素名定位元素。

● getElementsByClassName()方法:  通过页面元素的class属性值定位元素。

Use the getElementByld() method to locate page elements:

The id attribute of the HTML page element is unique and non-repeatable, so the HTML page element positioned in this way is also unique.

// 通过id名来对元素进行定位
        var btn = document.getElementById('btn');
        console.log(btn);

Use the getElementsByName() method to locate page elements:

// 通过页面中Class名来对元素进行定位;
        var btn = document.getElementsByClassName('btn');
        // 得到HTMLCollection集合 -> 类数组对象;
        console.log(btn);

Note: When using the getElementsByName() method to locate page elements, the correct writing is:

// 通过页面中Class名来对元素进行定位;
        var btn = document.getElementsByClassName('btn')[0];
        // 得到页面内类名为btn的元素;
        console.log(btn);

Use the getElementsByTagName() method:

<body>
    <button name="btns"></button>
    <button name="btns"></button>
    <button name="btns"></button>
    <button name="btns"></button>
    <button name="btns"></button>
    <script>
        // 通过页面中name属性名来对元素进行定位;
        var btn = document.getElementsByName('btns')[0];
        // 输出的是一个索引数组,NodeList;里面有5个button按钮;
        console.log(btn);
        console.log(btn instanceof NodeList); // true;
    </script>
</body>

Use the getElementsByClassName() method:

<body>
    <button></button>
    <button></button>
    <button></button>
    <button></button>
    <button></button>
    <script>
        // 通过页面中标签名来对元素进行定位;
        var btn = document.getElementsByTagName('button')[0];
        // 得到页面内标签名为button的元素;
        console.log(btn);
        console.log(btn instanceof HTMLCollection); // true
    </script>
</body>

Summary:
getElementsByName() method
getElementsByTagName() method
getElementsByClassName() method The
above three methods, add [0] after use, to facilitate the correctness of elements in practical applications;

Guess you like

Origin blog.csdn.net/weixin_46370455/article/details/108635385