Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

121
Vistas
issue with finding the next element jquery

I have a question about the behavior of next(), in the code below if I try to use next() to find the next span it works, but if I try to find the next div it doesn't work

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>

<div>
    <span>span 1 before</span>
    <a href="#button">button 1</a>
    <span>span 1 after</span>
    <div>div 1 after</div>
</div>
<div>
    <span>span 2 before</span>
    <a href="#button">button 2</a>
    <span>span 2 after</span>
    <div>div 2 after</div>
</div>

<script>
$("a").click(function () {
    // works:
    // alert($(this).next("span").text());

    // doesn't work:
    alert($(this).next("div").text());
});
</script>
about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

.next will select the next sibling if it matches the selector passed. Since the next sibling of the <a> is the <span>, .next will only work if you do .next('span').

If you want to select any following sibling, use .nextAll.

$("a").click(function() {
  console.log($(this).nextAll("div").text());
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>

<div>
  <span>span 1 before</span>
  <a href="#button">button 1</a>
  <span>span 1 after</span>
  <div>div 1 after</div>
</div>
<div>
  <span>span 2 before</span>
  <a href="#button">button 2</a>
  <span>span 2 after</span>
  <div>div 2 after</div>
</div>

Just to illustrate, switching the location of the span with the div also results in the div being found with .next.

$("a").click(function() {
  console.log($(this).next("div").text());
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>

<div>
  <span>span 1 before</span>
  <a href="#button">button 1</a>
  <div>div 1 after</div>
  <span>span 1 after</span>
</div>
<div>
  <span>span 2 before</span>
  <a href="#button">button 2</a>
  <div>div 2 after</div>
  <span>span 2 after</span>
</div>

about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda