paradigm111
paradigm111

Reputation: 396

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>

Upvotes: 0

Views: 71

Answers (1)

CertainPerformance
CertainPerformance

Reputation: 370599

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

Upvotes: 3

Related Questions