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

119
Views
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 answers
Answer question

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