Jahongir Rahmonov
Jahongir Rahmonov

Reputation: 13723

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?

Upvotes: 0

Views: 763

Answers (5)

markusthoemmes
markusthoemmes

Reputation: 3120

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

var selection = $('div[id^="leg-"]');
selection.next().remove();
selection.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.

Upvotes: 2

Adib Aroui
Adib Aroui

Reputation: 5067

You are not removing the next element only selecting it. Please to also add: $(this).next().remove(); before removing the div element. You can use jQuery.each(): https://jsfiddle.net/cdzswdrk/1/

// when document ready
    $('div[id^="leg-"]').each(function(){
      var $this= $(this);
      $this.next().remove();
      $this.remove();
    });

Upvotes: 1

Alessio Cantarella
Alessio Cantarella

Reputation: 5201

You could remove the hr by combining the jQuery next and remove functions in this way:

$(function() {
  $('div[id^="leg-"]').each(function(i, v) {
    $(v).next("hr").remove();
    $(v).remove();
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="leg-1">#leg-1</div>
<hr>
<div id="not-leg-1">#not-leg</div>
<hr>
<div id="leg-2">#leg-2</div>
<hr>

Upvotes: 1

Ankur Bhadania
Ankur Bhadania

Reputation: 4148

Try this First remove next <hr> element the remove selection element

$(document).ready(function(){
  var selection = $('div[id^="leg-"]');
  selection.next('hr').remove();
  selection.remove();


});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="leg-1">
  1
</div>
<hr>
<div id="leg-2">
  2
</div>
<hr>
<div id="">
  3 not leg
</div>
<hr>

Upvotes: 1

Mohammad
Mohammad

Reputation: 21489

You can select next hr of div using .next() and use .addBack() to adding div to jquery selector.

$("div[id^=leg-]").next().addBack().remove();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="leg-1">leg-1 text</div>
<hr>
<div>text</div>
<div id="leg-2">leg-2 text</div>
<hr>
<div>text2</div>

Upvotes: 2

Related Questions