简体   繁体   中英

Get index/position of element and it's Name in Javascript [ DOM ]

I try to find the index position and name of div element in container but whenever i try it is not give me the correct outPut.

<!DOCTYPE html>
    <html>
    <head>
    </head>
    <body>
    <div id="container">
    <div>This is div</div>
    <p>This is Paragraph</p>
    <script>
    let x = document.getElementById("container")
    let y = x.childNodes;
    for(let i =0; i < y.length ; i++)
    {
        if(y[i].nodeType == 2)
        {
            alert(y[i].nodeName);
            }
    }
    </script>
    </body>
    </html>

The nodeType property returns the node type, as a number, of the specified node.

If the node is an element node, the nodeType property will return 1.

If the node is an attribute node, the nodeType property will return 2.

If the node is a text node, the nodeType property will return 3.

If the node is a comment node, the nodeType property will return 8.

 let x = document.getElementById("container") let y = x.childNodes; for(let i =0; i < y.length ; i++) { if(y[i].nodeType == 1) { alert(y[i].nodeName); } }
 <!DOCTYPE html> <html> <head> </head> <body> <div id="container"> <div>This is div</div> <p>This is Paragraph</p> </div> </body> </html>

Based On the solution from MBadrian as far as you managed to get the nodeName then you can set your condition based on the Name of the Node, now if you want to get specific nodes you can get their text content and set your condition based on that... the below code is the same as MBadrian answer only I replaced the return of nodeName and returned the textContent

  let x = document.getElementById("container")
    let y = x.childNodes;
    for(let i =0; i < y.length ; i++)
    {
      console.log(y[i].nodeType)
        if(y[i].nodeType == 1)
        {
            alert(y[i].textContent);
            }
    }

The space bars, new lines and tabs between 2 tags are considered as one text node. So there is a node before inner DIV. Similarly, there is a text node between inner DIV and P element.

Checking the 'tagName' property of each child node inside for loop will also work. Text nodes do not have 'tagName' property.

<div id="container">
<div>This is div</div>
<p>This is Paragraph</p></div>
<script>
let x = document.getElementById("container")
let y = x.childNodes;
for(let i =0; i < y.length ; i++) {
    if(y[i].tagName && (y[i].tagName.toUpperCase() == "DIV" || y[i].tagName.toUpperCase() == "P")) {
        alert(i + ": " + y[i].innerHTML);
    }
}

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM