Search This Blog

Sunday, September 7, 2014

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

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:
 
Some content
More content
And you need to get not only
 
 
Some con... but
Some con...
Here is the code to get jQuery selector's HTML including its own:
 

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

Contact Form

Name

Email *

Message *