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:
- Cloning selected
div
- Creating a new
div
DOM object and appending created clone of thediv
- 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.
Why not just use $('#top').parent().html(); ?
ReplyDeleteBecause $('#top').parent() might have other children...
ReplyDeleteThanks~!
ReplyDeleteWorth noting that any functions you bound to your object in javascript will _not_ be preserved by rendering to HTML.
ReplyDeleteuse:
ReplyDelete$('#top').attr('outerHTML');
how can we remove a element inside a string "html" and also how to remove a element with a specific class
ReplyDeletehow About...
ReplyDelete$("#top")[0].outerHtml ?
Thanks for this tip.
ReplyDelete@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.
Nice man thanks!
ReplyDeletefabulouse!!!!
ReplyDeleteI really needed this to create a converting tool. you help me a lot! Thanks~~
ReplyDeletejQuery.fn.extend({
html2string: function() {
return $('<div>').append(this.clone()).remove().html();
}
});
helps a lot if you want to offer an embed code of an existing element that you are editing.
ReplyDeleteThanks
<input type="text" value="" id="videoEmbed"/>
$("#videoEmbed").val($("<div>").append($('#ytp').clone()).remove().html());
Worked for me. Thanks !
ReplyDeleteWhat about this
ReplyDeletevar curDiv = $("#somework");
var html = curDiv.wrap("<div/>").parent().html();curDiv.unwrap();
return html;
thanks
ReplyDelete$('#top').attr('outerHTML');
ReplyDeleteThanks man, it works!
super......
ReplyDeleteThanks.
ReplyDelete