Jack Kiurre
Jack Kiurre

Reputation: 17

Show all DOM nodes in html div

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

Upvotes: 1

Views: 1723

Answers (3)

ellipsis
ellipsis

Reputation: 12152

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>

Upvotes: 0

Mamun
Mamun

Reputation: 68933

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>

Upvotes: 2

Nithya Rajan
Nithya Rajan

Reputation: 4884

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>

Upvotes: 0

Related Questions