Monday, February 2, 2009

How to get full html string including the selected element itself with jQuery's $.html()

Sometimes you need to get the selected element's html as well when using .html() function. To make it more clear what I mean, consider you have this HTML markup:

<div id="top">
  <div id="inner">
    Some content
  </div>
  More content
</div>

And you need to get not only <div id="inner">Some con... but <div id="top"><div id="inner">Some con...

Here is the code to get jQuery selector's HTML including its own:

var html = $('<div>').append($('#top').clone()).remove().html();

Here we are:

  1. Cloning selected div
  2. Creating a new div DOM object and appending created clone of the div
  3. Then getting the contents of wrapped div (which would give us all HTML)
  4. Finally removing the created DOM object, so it does not clutter our DOM tree.

This is a little trick you can use to select self HTML with jQuery's .html() function. But if you can you should surround your markup with some dummy div and avoid this workaround all together. This would be much faster since jQuery would not need to do all the DOM manipulations.

18 comments:

  1. Why not just use $('#top').parent().html(); ?

    ReplyDelete
  2. Because $('#top').parent() might have other children...

    ReplyDelete
  3. Worth noting that any functions you bound to your object in javascript will _not_ be preserved by rendering to HTML.

    ReplyDelete
  4. use:
    $('#top').attr('outerHTML');

    ReplyDelete
  5. how can we remove a element inside a string "html" and also how to remove a element with a specific class

    ReplyDelete
  6. how About...

    $("#top")[0].outerHtml ?

    ReplyDelete
  7. Thanks for this tip.

    @Ben: The fact that bound callbacks are discarded is presicely why I use this "trick". A simple .clone(true).unbind() did not seem to get rid of all callbacks, unfortunately.

    ReplyDelete
  8. I really needed this to create a converting tool. you help me a lot! Thanks~~


    jQuery.fn.extend({
    html2string: function() {
    return $('<div>').append(this.clone()).remove().html();
    }
    });

    ReplyDelete
  9. helps a lot if you want to offer an embed code of an existing element that you are editing.
    Thanks

    <input type="text" value="" id="videoEmbed"/>

    $("#videoEmbed").val($("<div>").append($('#ytp').clone()).remove().html());

    ReplyDelete
  10. Worked for me. Thanks !

    ReplyDelete
  11. What about this

    var curDiv = $("#somework");
    var html = curDiv.wrap("<div/>").parent().html();curDiv.unwrap();
    return html;

    ReplyDelete
  12. $('#top').attr('outerHTML');

    Thanks man, it works!

    ReplyDelete