shenkwen
shenkwen

Reputation: 3880

Need some clarification about jQuery objects that don't reside in the DOM

I was trying to use browser console to do some HTML code manipulation. In console, I input

s = $('<div><span>ddd</span></div>');
s.remove('span');

Be noted the jQuery object s is not in the DOM, it only lives in the console. It turns out the span isn't removed from s. On the other hand, if <div><span>ddd</span></div> was in HTML, the span will surely be removed.

This brings up a question that has been confusing me for a long time. If I understand right, using $(), I can turn many things into jQuery objects, even if they are not actually in the DOM. But what is the difference between this kind of jQuery objects and the those jQuery objects that are linked to some DOM elements? And in the above code, in order to actually remove the span and get an output as <div></div>, do I have to write it into DOM?

Upvotes: 1

Views: 29

Answers (1)

dfsq
dfsq

Reputation: 193301

It's because you are not using $.fn.remove properly. Correct way to remove child span is to find it first:

s = $('<div><span>ddd</span></div>');
s.find('span').remove();

When you provide a selector to remove, jQuery filters supplied collection by this selector. However, in your case there is nothing that can be filtered out, since clearly div is not span. So s.remove('span'); removes nothing.

Upvotes: 2

Related Questions