JavaScript Dom: Find Element Index in Container

JavaScript DOM: Find Element Index In Container

You could make usage of Array.prototype.indexOf. For that, we need to somewhat "cast" the HTMLNodeCollection into a true Array. For instance:

var nodes = Array.prototype.slice.call( document.getElementById('list').children );

Then we could just call:

nodes.indexOf( liNodeReference );

Example:

var nodes = Array.prototype.slice.call( document.getElementById('list').children ),    liRef = document.getElementsByClassName('match')[0];
console.log( nodes.indexOf( liRef ) );
<ul id="list">    <li>foo</li>    <li class="match">bar</li>    <li>baz</li>    </ul>

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

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);
}
}

Find the index of a div inside a container

You can do the following,

$('.handler').click(function(e) {
var el = e.target;
console.log([].indexOf.call(el.parentNode.parentNode.children, el.parentNode));
});

However if you want to know what was wrong in your code,

Array.prototype.indexOf.call($('.container')[0].children, $(this).parents('.block')[0])

This part should fix the problem in your code. You have been doing it all right, but for the parameter of indexOf we needed the children array of .container and clicked element.

You were passing the container element and current clicked element as an array. That is Array.prototype.indexOf.call('[Container Element]', ['current clicked div']) Which is not right. You should pass something like this,
Array.prototype.indexOf.call('[children, children, children...]', 'current clicked div element').

It was happening because the $('.container') returns an array with the element having a class name .container. But we needed all the children array of the element that contains container class.

And $(this).parents('.block') returns an array with the matching elements even if it is only one.

How to get specific element inside of element stored in variable?

There are several ways:

let anchors = productAttachedFilesModal.getElementsByTagName("a");

let anchors = document.querySelectorAll("#modal_more_information > a")

let anchors = productAttachedFilesModal.querySelectorAll("a");

Get child node index

you can use the previousSibling property to iterate back through the siblings until you get back null and count how many siblings you've encountered:

var i = 0;
while( (child = child.previousSibling) != null )
i++;
//at the end i will contain the index.

Please note that in languages like Java, there is a getPreviousSibling() function, however in JS this has become a property -- previousSibling.

Use previousElementSibling or nextElementSibling to ignore text and comment nodes.

Get index of clicked element using pure javascript

Here is a piece of code that can help you get the index of the clicked element inside the for loop. All you need is a new scope:

var g = document.getElementById('my_div');
for (var i = 0, len = g.children.length; i < len; i++)
{

(function(index){
g.children[i].onclick = function(){
alert(index) ;
}
})(i);

}

Edit 1: Incorporating user Felix Kling's comments into the answer.

event handler already is a closure

Edit 2: Updated fiddle link

Is it possible to get element's numerical index in its parent node without looping?

You could count siblings...
The childNodes list includes text and element nodes-

function whichChild(elem){
var i= 0;
while((elem=elem.previousSibling)!=null) ++i;
return i;
}


Related Topics



Leave a reply



Submit