Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

120
Visualizações
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 Respostas
Responde à pergunta

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda