brentonstrine
brentonstrine

Reputation: 22752

Removing a class from the DOM also removes it from items in variables

When I use

$('span').removeClass('reallyRed');

to remove a class from the DOM, it does so. Yay! But if I have pushed HTML elements into a variable with myVar.push(this) then the .removeClass() also finds the classes in myVar and removes them from the variable too!

Here is the JSFiddle. Why does this happen? I suspect it has something to do with how jQuery looks at the DOM, but it might be an issue with how I am using .push() within an .each() loop.

Upvotes: 2

Views: 56

Answers (1)

Ionică Bizău
Ionică Bizău

Reputation: 113385

Use clone() function to make a copy of the element when pushing it into variable:

myVar.push($(this).clone()[0]);

Let's take an example:

var obj = {
    "key1": "val1",
    "key2": "val2",
    "key3": "val3"
};

var array = [];
array.push(obj);
console.log(obj); // { "key1": "val1", "key2": "val2", "key3": "val3"}
delete array[0].key1;
console.log(obj); // { "key2": "val2", "key3": "val3"}

This is happening because the object has the same reference (array[0] === obj before and after deleting the first key).

This is why you need the clone() jQuery function.

From documentation:

.clone()

Create a deep copy of the set of matched elements.

Your javascript code becomes:

$('div').each(function(e) {
    myVar.push($(this).clone()[0]);
});

JSFIDDLE

Upvotes: 4

Related Questions