I have mark up like
<div id="div1">
<div id="div2">
blah blah
</div>
</div>
If I use $("#div1").html(), it returns the div#div2. But I want to get the complete html. i.e, along with div#div1.
Is there any way to do this?
I have mark up like
<div id="div1">
<div id="div2">
blah blah
</div>
</div>
If I use $("#div1").html(), it returns the div#div2. But I want to get the complete html. i.e, along with div#div1.
Is there any way to do this?
You could try:
$('#div1')[0].outerHTML
EDIT:
The same solution but without using jQuery (better performance):
document.getElementById('div1').outerHTML
I would say try to select the parent element, or the other way is to do this:
var html = $('<div>').append($('#top').clone()).remove().html();
Use .parent():
$("#div1").parent().html();
However this will also get the html for all siblings. You could just wrap div1 in another div... :)
Try this : http://jsfiddle.net/96u9c/3/
:)
special need function, now you can use it for any purpose of your own.
justtext
will get you the only text for parent tag where as inner
version will get you children text.
Hope it helps :)
You could very well add this to your common javascript file in project or customize it and use it as a plugin in your project.
code
jQuery.fn.justtext = function() {
return $(this).clone()
.children()
.remove()
.end()
.text();
};
jQuery.fn.justtextinner = function() {
return $(this).clone()
.children()
.end()
.text();
};
alert($('#div1').justtextinner());
You could create a simple jQuery plugin that would do the job for you, allowing you to use the native .outerHTML
property when it exists, or polyfill it when it doesn't.
(function($) {
if('outerHTML' in document.createElement('div')) {
$.fn.outerHtml = function() {
return this[0].outerHTML;
}
}
else {
$.fn.outerHtml = function() {
return $("<div />").append(this.eq(0).clone()).html();
}
}
}(jQuery));
An example is at http://jsfiddle.net/steveukx/qUEyp/