Finnnn
Finnnn

Reputation: 3580

jquery remove removing from another element

According to here, jquery's remove function should work like so..

$('div').remove('selector'); 

Which I'm trying in this example.

HTML:

<div class="wrapper">
    <p class="unwanted">This should be removed</p>
    <p class="retained">This will remain</p>
</div>​

JavaScript:

jQuery(document).ready(function($) {
    $('div').remove('p.unwanted'); //not working
    //$('p.unwanted').remove(); //this works
});

​ It's not working. What am I doing wrong?

Upvotes: 1

Views: 1430

Answers (4)

Codegiant
Codegiant

Reputation: 2150

try this

 $(document).ready(function() {
    $('div').find('p.unwanted').attr('class', '');
});

Upvotes: 0

Bugs
Bugs

Reputation: 1452

You're trying to remove something that is both div and p.unwanted. The filter in remove() is applied to the current set of nodes, which in this case is all div elements.

Use the children set instead:

$('div').children().remove('p.unwanted');

Upvotes: 1

Anthony Grist
Anthony Grist

Reputation: 38345

You've misunderstood what the documentation is saying. It's not looking for elements that are descendants of the matched elements that match the selector, it's simply filtering down the set of already matched elements to those that match the selector, and then removing them.

If you have this HTML:

<div class="wanted">Some text</div>
<div class="wanted">Some more text</div>
<div class="unwanted">Some unwanted text</div>

and then executed this jQuery:

$('div').remove('.unwanted');

then it would only remove that third <div> (the one with the unwanted class on it), because it first selects all <div> elements, and then only removes those that match the selector.

Example jsFiddle

Upvotes: 1

VisioN
VisioN

Reputation: 145398

You should use the following:

$('p').remove('.unwanted');

Argument in remove works as a filter. So here, you first select all <p> elements and then remove only those which have class unwanted.

DEMO: http://jsfiddle.net/qwXSw/1/

Upvotes: 0

Related Questions