Not sure if the title is right, please suggest changes if you disagree.
I was working with content loaded via jquery (.load()) into a div. I had to remove couple items from the loaded content. I’ve done so in the same manner as in the jsfiddle example I wrote ( http://jsfiddle.net/AzxaL/12 ). This one does not use load() function which creates id duplication, but this is irrelevant.
The question is: why one work and another does not and what needs to change in
else if(this.tagName == ‘H2’) {
$(this).remove();
}
of the not working example?
To save you hunting down differences, the only one is in the /* line of interest */
Working
$('#copy_working_box').html($('#copy_working_box').children('#wrapper').children()).fadeIn(300);
Not working
$('#copy_working_not_box').html(content).fadeIn(300);
Also, please notice that in the not working example the div#subcontent does get removed it is only the h2 that is not.
P.S. I’m looking for clarification as I understand that this issue exists only because of my flawed understanding of how this example works.
Thanks in advance.
When you do this:
you get a jQuery object containing a list of elements at the time the code is run. That list isn’t dynamic, so removing one (or more) of those elements from the DOM (using
.remove()) doesn’t update the list of elements in the object. However, changes to the content of those elements are reflected as your jQuery object contains references to the DOM elements.When you select elements using the jQuery function, in this case with the following code:
what you end up with is a jQuery object containing the references to the corresponding DOM elements. jQuery objects are array-like (they have a
lengthproperty, and individual elements can be accessed using the square bracket notation[0]) so for our purposes we can think of it simply as an array of elements.Given the HTML that we’re working with, that array would consist of a
<h2>element and a<div>element with theidofcontent. For the purposes of illustration, we’ll represent that like so:Now, we’re dealing with two cases in your code.
In case one, we start with the reference to the element in our jQuery object; that’s the
<div#content>element. We then access its children –[<p>, <div#subcontent>], filter that down to just the<div#subcontent>and remove it. Since our array still has a reference to<div#content>, and that in turn has references to its descendents, this change to the DOM will affect it (the reference to the child<div#subcontent>is removed from<div#content>).In case two, we start with the reference to the element in our jQuery object; that’s the
<h2>element. We then simply remove this element – that removes it from the DOM, so any references to it in other DOM elements (i.e. its ancestors) will be updated. However, we still have a reference to the DOM element itself stored in our jQuery object.