Jahongir Rahmonov Jahongir Rahmonov - 3 months ago 8x
jQuery Question

Remove the next element together with the selected one in jquery

I am bulk deleting all

elements with the id that starts with


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

<div id="leg-1">


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


How can I do this?


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

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

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.