Home > Mobile >  Where is the position of the child element? - jquery
Where is the position of the child element? - jquery

Time:02-14

how can i get child element position in JQuery? I want to get the number 2 in the alert, because it is the second child!

function where_am_i(element) {
  alert("your position is:"   $(element).position_element());
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<ul>
  <li>one</li>
  <li onclick="where_am_i(this)">two</li>
  <li>three</li>
</ul>

CodePudding user response:

Use jQuery's .index() method. Note that it returns a zero-based index so you'll need to add one to get the value you want.

$("ul li").on("click", function() {
  alert(`your position is: ${$(this).index()   1}`)
})
li { margin: 1rem auto; cursor: pointer; }
li:hover { text-decoration: underline; }
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.slim.min.js"></script>
<ul>
  <li>one</li>
  <li>two</li>
  <li>three</li>
</ul>


As always, you might not need jQuery

document.querySelector("ul").addEventListener("click", e => {
  const target = e.target.closest("li")
  if (target) { // clicked on an <li>
    const siblings = Array.from(target.parentElement.children)
    const position = siblings.indexOf(target)   1
    alert(`your position is: ${position}`)
  }
})
li { margin: 1rem auto; cursor: pointer; }
li:hover { text-decoration: underline; }
<ul>
  <li>one</li>
  <li>two</li>
  <li>three</li>
</ul>

CodePudding user response:

EDIT: Phil's solution is much better

Get the parent, get all the parent's children, then find the index of the inputted element within the array of child nodes.

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<ul>
    <li>one</li>
    <li onclick="findElem(this)">two</li>
    <li>three</li>
</ul>

<script>
    const findElem = (elem) => {
        // Grab the parent element
        const parent = $(elem).parent();

        // Get array of all its children
        const allChildren = $(parent).children();

        // Turn it into a regular array, find the index of our elem, add 1 to it
        const position = [...allChildren].indexOf(elem)   1;

        console.log(`The clicked element's position is ${position}`);
    };
</script>

  • Related