Tim
Published

Mon 27 January 2014

←Home

jQuery outerHTML plugin

Let's say you'd like a stringified version of an HTML node. Every DOM object has a built-in .innerHTML attribute, which can give you a string version of its contents. What's sucky is that this fails to include the node itself.

This little jQuery plugin adds an .outerHTML() method to jQuery objects, which will return the full string version of the first HTML node it contains, including its attributes.

Here's the code.

// jquery.outerhtml.js

jQuery.fn.outerHTML = function() {
    return this
      // We're only going to support one node
      .first()
      // In order not to add markup to the page, we first clone the node
      .clone()
      // Since we need to wrap it (the tag is arbitrary)
      .wrap('<div />')
      // Wrap returns the child, so get a handle on the new parent
      .parent()
      // Then get a handle on the actual HTML node (not the jQuery object)
      .get(0)
      // And finally get and return the innerHTML of the node.
      .innerHTML;
};

Feel free to use this for any purpose whatsoever. Don't even attribute anything. It's public domain.

Go Top
comments powered by Disqus