How to get the contents of an object of an Object?

I want the #post content to include myself. The jQuery html () method returns only content that does not include itself. Trying to get the parent html object does not work in all situations, because this object may have siblings.

What is the solution for this?

<div id="post"> <div>content</div> <div> <div></div> 
+4
source share
5 answers

Description

jQuery html() gives you only innerHTML right. You can do

 $("#post")[0].outerHTML 

to get the full html , but this is not compatible with the browser .

Take a look at the jsFiddle Demo

You can use this plugin to get the cross-browser compatible function .outerHTML()

Additional Information

+4
source

You can clone a given element and add a clone to a new element. Then you can get the HTML code for the new element:

 var html = $("<div>").append($("#post").clone()).html(); 
+2
source

you can wrap use a virtual div using clone to infect you do not bother the DOM .

you can try like this

 $('#post').clone().wrap('<div>').parent().html(); 
+2
source
 if (!Element.prototype.hasOwnProperty("outerHTML")) { Object.defineProperty(Element.prototype, "outerHTML", { configurable: true, get: function getOuterHTML() { var html = this.innerHTML; var tag = "<" + this.tagName; var closeTag = "</" + this.tagName + ">"; [].forEach.call(this.attributes, function (attr) { tag += attr.nodeName + '="' + attr.nodeValue + '"'; }); tag += ">"; return tag + html + closeTag; } }); } 

If outerHTML is not upstream, you should pin it. That means you can just do

document.getElementById("post").outerHTML;

Demo

+1
source

Maybe something like this:

 var elem = $("#post").clone().wrap('<div>').parent().html(); 

Fiddle!

0
source

Source: https://habr.com/ru/post/1391134/


All Articles