Skip to content Skip to sidebar Skip to footer

How To Get Dom Object's Content Include Itself?

I want to able to get #post content include itself. jQuery's html() method only return content that does not include itself.Trying to get parent object's html does not work in all

Solution 1:

Description

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

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

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

Check out this jsFiddle Demonstration

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

More Information

Solution 2:

You can clone the element in question and append the clone to a new element. Then you can get the HTML of the new element:

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

Solution 3:

you can wrap it around a virtual div using clone so infect you wont disturb the DOM.

you can try like this

$('#post').clone().wrap('<div>').parent().html();

Solution 4:

if (!Element.prototype.hasOwnProperty("outerHTML")) {
  Object.defineProperty(Element.prototype, "outerHTML", {
    configurable: true,
    get: functiongetOuterHTML() {
      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 precent the following should shim it. This means you can just do

document.getElementById("post").outerHTML;

Demo

Solution 5:

Maybe something like this:

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

Fiddle!

Post a Comment for "How To Get Dom Object's Content Include Itself?"