Does jQuery wrap () only work on the DOM and not on a jQuery object?

Considering the following code in javascript with jQuery:

var inner = $('<p></p>')
var outer = inner.wrap('<div></div>')

console.log(inner.outerHTML())       // <p></p>
console.log(outer.outerHTML())       // <p></p>

      

I understand the first conclusion. .wrap()

returns the original object for the chain.

For the second output, I would expect <div><p></p></div>

, since the function .wrap()

needs to modify / expand the variable inner

.

Does it .wrap()

only work on DOM elements? Not on a newly created jQuery object?

Using Chorme with jQuery 2.1.1

+3


source to share


2 answers


.wrap()

works also with jQuery objects that don't reference anything to the DOM, eg $('<p></p>')

.

But you have to ask the result correctly. Because of the chaining, you only get the original jQuery object, but you need to ask for the newly created elements around it .parents()

to get the expected result.

$('<p></p>').wrap('<div></div>').parents()

will give: <div><p></p></div>




notes from OP

It was obvious that I had not received this before, but due to the response and comments from @ jfriend00, I began to understand it. Also, I doubted that the jQuery object was just a reference to something in the DOM, or it could be something new.

+3


source


.wrap()

returns the same jQuery object you originally called. The DOM has been modified, but the jQuery object has not been modified. And since you used .wrap()

, the element itself and its children, which are what it returns .outerHTML()

, have not changed either. Only the parent node is changed, which is not a part .outerHTML()

, so you don't see any changes.

Quoted from the jQuery doc for.wrap()

:

This method returns the original stencil for the chain.

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. Changing the structure around these DOM elements doesn't change the jQuery object in any way. It still contains the same DOM objects.


So with the above in mind, an outerHTML query for a static set of DOM elements will return the same result if you've wrapped it in some other element or not. You are looking at the element itself and children with outerHtML. This hasn't changed at all since .wrap()

.

+1


source







All Articles