I want to show all the nodes of my html page inside a div.
What i have so far (js):
var nodes = document.getElementsByTagName("*");
div3.innerHTML = nodes;
And html:
<body>
<div id="content">
<div id="1-1">
<div id="div1"></div><br>
<div id="div2"></div><br>
<div id="div3"></div><br>
<div id="div4"></div><br>
<div id="div5"></div>
</div>
</div>
<script src="script201.js" rel="text/javascript"></script>
</body>
The output I get from this code in div3: [object HTMLCollection]
How do I get all the nodes to show like:
BODY
DIV
DIV
DIV
DIV
DIV
DIV
DIV
SCRIPT
So every node in the file basically
You have to loop through all the nodes so that you get the nodeName property individually.
Please Note: Since document object has some other tags like HTML
, HEAD
, STLYLE
, SCRIPT
etc., all of them will be targeted with *
selector.
var nodes = [...document.getElementsByTagName("*")]; nodes.forEach(function(el){ div3.innerHTML += el.nodeName + ' '; })
<body> <div id="content"> <div id="1-1"> <div id="div1"></div><br> <div id="div2"></div><br> <div id="div3"></div><br> <div id="div4"></div><br> <div id="div5"></div> </div> </div> <script src="script201.js" rel="text/javascript"></script> </body>
Use element_name.querySelectorAll('*')
to get all elements inside it.
var b=document.getElementById('div3') document.querySelectorAll('*').forEach(e=>b.innerHTML+=e.nodeName + "<br>")
<body> <div id="content"> <div id="1-1"> <div id="div1"></div><br> <div id="div2"></div><br> <div id="div3"></div><br> <div id="div4"></div><br> <div id="div5"></div> </div> </div> <script src="script201.js" rel="text/javascript"></script> </body>
You can use JavaScript querySelectorAll
method, which is used to select all the nodes based on the parameter we passed. for example if we pass * inside document.querySelectorAll('*')
, it selects all the node in the document. "*" is the universal selector.
var allNode=document.querySelectorAll('*') console.log(allNode)
<body> <div id="content"> <div> <div id="div1"></div><br> <div id="div2"></div><br> <div id="div3"></div><br> <div id="div4"></div><br> <div id="div5"></div> </div> </div> <script src="script201.js" rel="text/javascript"></script> </body>
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.