jm2
jm2

Reputation: 763

jQuery remove: $("...").remove() vs .remove("...")

Reading the docs, I'd expect $("#wrap2").remove(".error") to remove all .error elements from #wrap2. However looking at this JSFiddle: http://jsfiddle.net/hCGUS/ it doesn't appear to be the case?

$(function() {
    $("#wrap1 .error").remove(); // works 
    $("#wrap2").remove(".error"); // fails ...
})​

Upvotes: 3

Views: 554

Answers (5)

Yong
Yong

Reputation: 758

According to the jQuery document. I think

$("#wrap2").remove(".error");

equals to:

$("#wrap2.error").remove();

Means that an element has id wrap2 and class error

Upvotes: 3

Bunlong
Bunlong

Reputation: 662

Please use removeClass instead of remove

$("#wrap2").removeClass("error");

Upvotes: -3

Evan Mulawski
Evan Mulawski

Reputation: 55354

Building off of x1a4's answer, $("wrap2") only contains one element, not any of its children. If you did:

$("wrap2 *").remove(".error")

it would perform identically to your working version.

Upvotes: 1

Michael Mior
Michael Mior

Reputation: 28752

As the docs state, the selector parameter to remove is

A selector expression that filters the set of matched elements to be removed.

The first example is what you should use to remove elements with class error contained in an element with id wrap1.

The second example will find the element with id wrap2 and then filter that set for elements with class error, and remove those elements. That is, it will only remove elements which match #wrap2.error.

Upvotes: 8

x1a4
x1a4

Reputation: 19485

The docs say that when passing an argument, it acts as a filter on the wrapped set it's being called on, so if you have a jQuery set, but only want to remove some of the elements in the set, you can pass a selector to remove just those.

Upvotes: 3

Related Questions