Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

186
Views
¿Dónde está la posición del elemento hijo? - jquery

¿Cómo puedo obtener la position del elemento secundario en JQuery? ¡Quiero obtener el número 2 en la alerta, porque es el segundo niño!

 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>

about 4 years ago · Juan Pablo Isaza
2 answers
Answer question

0

Utilice el método .index() de jQuery. Tenga en cuenta que devuelve un índice basado en cero, por lo que deberá agregar uno para obtener el valor que desea.

 $("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>


Como siempre, es posible que no necesite 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>

about 4 years ago · Juan Pablo Isaza Report

0

EDITAR: la solución de Phil es mucho mejor

Obtenga el padre, obtenga todos los hijos del padre, luego busque el índice del elemento ingresado dentro de la matriz de nodos secundarios.

 <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>

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!