Get all elements in the body tag using pure javascript

前端 未结 2 1407
眼角桃花
眼角桃花 2020-11-30 05:46

I\'m trying to get all the elements (tags) inside the Body tag of an HTML page in an array using pure javascript. I mean without using any framework (ex. JQuery).

I

相关标签:
2条回答
  • 2020-11-30 06:08

    If you want all elements inside the body tag, not just first level children, you can simply use getElementsByTagName() with a wildcard:

    var elems = document.body.getElementsByTagName("*");
    
    0 讨论(0)
  • 2020-11-30 06:19

    You can use document.querySelectorAll() for that.

    If you really want all (including nested tags), use this

     var elements = document.querySelectorAll( 'body *' );
    

    If you only want the immediate child nodes, use

     var elements = document.querySelectorAll( 'body > *' );
    
    0 讨论(0)
提交回复
热议问题