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:
Here we are:
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:
And you need to get not onlySome contentMore content
Here is the code to get jQuery selector's HTML including its own:Some con... but
Some con...
var html = $('').append($('#top').clone()).remove().html();
Here we are:
- Cloning selected div
- Creating a new div DOM object and appending created clone of the div
- Then getting the contents of wrapped div (which would give us all HTML)
- 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.
No comments:
Post a Comment