Given the following code in javascript with jQuery:
var inner = $(\'\')
var outer = inner.wrap(\'\')
console.log(inner
.wrap()
returns the same jQuery object that you originally called it on. The DOM has been modified, but the jQuery object has not been modified. And, since you used .wrap()
the element itself and it's children which is what .outerHTML()
returns was not changed either. Only the object's parent node was changed which is not part of .outerHTML()
so thus you see no change.
Quoted from the jQuery doc for .wrap():
This method returns the original set of elements for chaining purposes.
Thus, when you do this:
var outer = inner.wrap('<div>','</div>');
outer
will be the same jQuery object as inner
so, of course, they will show the same .outerHTML()
.
A jQuery object is just a static list of DOM elements. Internally, it just contains an array of DOM elements. Modifying the structure around those DOM elements does not change the jQuery object in any way. It still contains those same DOM objects.
So, given the above, requesting the outerHTML of a static set of DOM elements will return the exact same result whether you've wrapped it in some other element or not. You're looking at the element itself and it's children with outerHtML. That didn't change at all with .wrap()
.
.wrap()
works also on jQuery objects that do not reference anything in the DOM, like $('<p></p>')
.
But you have to properly ask the result. Due to chaining, you only get the original jQuery object, but you have to ask for the newly created elements around it with .parents()
to get your expected result.
$('<p></p>').wrap('<div></div>').parents()
will give: <div><p></p></div>
notes from the OP
It's was obvious I was not getting it before, but due to the answer and comments from @jfriend00 I became to grasp it. Also I was in doubt if a jQuery object is only a reference to something in the DOM or could be something entirly new.