Several ways to get elements from BOM

2.1 How to get page elements

  1. Get getElementById according to id

    <div id="time">2023-08-01</div>
        <script>
            // 1.因为我们从文档页面从上往下加载,所以得先有标签,所以我们script写到标签下面
            // 2.get 获得element 元素 by 通过 
            // 3.参数id是大小写敏感的字符串
            // 4.返回的是一个元素对象
            var timer = document.getElementById('time');
            console.log(timer);
            console.log(typeof timer);
            // 5.   console.dir(timer)打印我们返回的元素对象 更好的查看里面的属性和方法
            console.dir(timer)
        </script>
    
  2. Get by tag name

    Use the getElementByTagName() method to return a collection of objects with the specified tag name

    Notice:

    1. Because what we get is a collection of objects, we need to traverse if we want to operate the elements inside
    2. get element object is dynamic
     <ul>
            <li>2</li>
            <li>2</li>
            <li>2</li>
            <li>2</li>
            <li>2</li>
        </ul>
        <script>
            // 1.返回的是 获取过来元素对象的集合 以伪数组的形式存储的(只有length 下标这边属性 其他的push那些是没有的)
            var lis = document.getElementsByTagName('li');
            console.log(lis);
            console.log(lis[0]);
            // 2.我们想要依次打印里面的元素对象我们可以采取遍历的方式
            for (let i = 0; i < lis.length; i++) {
          
          
                console.log(lis[i]);
                // 3.如果页面中只有一个li,返回的还是这个伪数组的形式
                // 4.如果页面中没有这个元素,返回的是空的伪数组形式
    
            }
        </script>
    
  3. Obtained by the new method of HTML5

    1. document.getElementByClassName('class name'); //Return the collection of element objects according to the class name

      // 通过document.getElementsByClassName根据类名获取某些元素的集合
              var boxs = document.getElementsByClassName('box');
              console.log(boxs); //HTMLCollection(2) [div.box, div.box]
      
    2. document.querySelector('selector') //Returns the first element object of the specified selector, remember that the selector inside needs to be marked.box #nav etc.

       // querySelector返回指定选择器的第一个元素对象
              var firstBox = document.querySelector('.box');
              console.log(firstBox);
              var nav = document.querySelector('#nav');
              console.log(nav); //div#nav
      
    3. document.querySelectorAll('selector')// return according to the specified selector

       // querySelectorAll ()返回指定选择器所有元素对象的集合
              var allBox = document.querySelectorAll('.box');
              console.log(allBox);
              var lis = document.querySelectorAll('li');
              console.log(lis);
      
  4. Special element acquisition

    1. Get the body element

      document.body //return body element object

    2. get html object

      document.documentElement //return html element object

Guess you like

Origin blog.csdn.net/qq_46372132/article/details/132120965