Skip to content Skip to sidebar Skip to footer

Calculate Div's Position Within A Div

Good day, I need some help in JS please. Say I have this HTML:

Solution 1:

You need to send the current clicked element to the function like

<divonclick="countPos(this)"></div>

Then in the function you can create an array of the elements inside the parent then find the index.

functioncountPos(elem){
  var nodeList = Array.prototype.slice.call( elem.parentNode.children );
  var index = nodeList.indexOf( elem ) + 1;
  // do your stuff with index
}

FIDDLE

Solution 2:

I would suggest giving each div an id, and passing that value to the JS function. Something like...

<div><divid="div1"onclick="countPos(this.id)"></div><divid="div2"onclick="countPos(this.id)"></div><divid="div3"onclick="countPos(this.id)"></div></div>

Post a Comment for "Calculate Div's Position Within A Div"