Question

<div><a href="" class="deleteNextSomething">Delete Something!</a></div>
<div class="something">This is Something</div>

Obviously, I could just do this:

$('.deleteNextSomething').click(function() {
 $(this).parent('div').next('.something').remove();
});

But, what if my HTML is actually more like this:

<div><div><div><a href="" class="deleteNextSomething">Delete Something!</a></div></div></div>
<div class="something">This is Something</div>

Point is, I don't want to know how many parents I need to go UP before I start going ACROSS. I just want to traverse the DOM in a "next" direction" until I hit the next node I'm looking for.

Does anyone know how to solve this? pleasssse.

Additional info. In this next example, I would want it to delete Something1. So I can't say parents('div').next - because this would ignore the very next element.

<div>
    <a href="" class="deleteNextSomething">Delete Something!</a>
    <div class="something">This is Something 1</div>
</div>
<div class="something">This is Something 2</div>
Was it helpful?

Solution

If you want to look at the "nearest" next, it would be something like this, using .parents() to go to all parents, instead of just the first level:

$('.deleteNextSomething').click(function() {
  $(this).parents('div').next('.something:first').remove();
});

You can test it out here. Since they're in reverse order after the .next() call, you want the :first one it finds, which would be the most local to the this you started with.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top