Jahongir Rahmonov Jahongir Rahmonov - 4 months ago 10
jQuery Question

Remove the next element together with the selected one in jquery

I am bulk deleting all

div
elements with the id that starts with
leg-
:

$('div[id^="leg-"]').remove();


I also want to delete
<hr>
element that comes after each div:

<div id="leg-1">
...
</div>

<hr>


There is no event fired that's why, I am unable to select the element like this:

$(this).next();


How can I do this?

Answer

You can cache the selection made by jQuery in an intermediate variable like following:

var selection = $('div[id^="leg-"]');
selection.remove();
selection.next().remove();

Like in the $(this) methodology you wanted to use, the variable selection now contains a reference to all the divs you want to remove. Calling next() on that selection returns the immediate sibling, thus the hr you want to delete, for each of those div.

In general: Wherever you need the same selection in jQuery twice, consider saving it to a variable to speed up your scripts and reduce DOM querying to a minimum.