val - jquery text()

Difference between using.html() and.contents() (2)

What's the difference between using these two jQuery snippets?

.append( $(this).contents() );
// and
.append( $(this).html() );

Yes, they're entirely different

  • .contents() gives you a jQuery object containing all the child DOM nodes of the element.

  • .html() gives you a string of HTML rendered from the descendant nodes of the element.

So when you .append() the contents(), you're relocating the nodes to a new location.

When you .append() the .html(), you're generating new nodes from the HTML string.

Keep in mind that on the client side, there is no HTML. You only have the DOM.

Considering that...

  • ...when you do .html(), what's happening is that all the descendant DOM nodes are being analyzed, and an HTML string is being created and returned.

  • ...when you do .html('<b>some HTML content</b>'), the HTML string itself isn't added to the DOM, but rather the string is parsed, and new DOM nodes are generated, which are then added to the DOM.

Based on a comment about cutting and copying, it sounds as though you still think you're working with the original HTML string sent from the server.

You're not.

You're working with JavaScript objects (well, host objects) that are nested within each other to form a hierarchy of objects (parents, children, grandchildren, etc). You can relocate a section of that hierarchy to another location within the hierarchy.

This hierarchy of elements is called the DOM, or Document Object Model.

Unfortunately, since jQuery's .append() accepts an HTML string, it adds to the illusion that you're actually dealing with HTML markup instead of objects.

So I'll state it again...

  • .html() generates a new HTML string. When you give the string to .append(), it will create new nodes based on that string, and insert them.

  • .contents() simply selects the existing nodes, and inserts them. Since a node can't be in two locations at the same time, the nodes are relocated to the location in the DOM where they are being appended.