[javascript] How to get the HTML for a DOM element in javascript

Imagine I have the following HTML:

<div><span><b>This is in bold</b></span></div>

I want to get the HTML for the div, including the div itself. Element.innerHTML only returns:

<span>...</span>

Any ideas? Thanks

This question is related to javascript html dom

The answer is


var x = $('#container').get(0).outerHTML;

old question but for newcomers that come around :

document.querySelector('div').outerHTML


Use outerHTML:

var el = document.getElementById( 'foo' );
alert( el.outerHTML );

First, put on element that wraps the div in question, put an id attribute on the element and then use getElementById on it: once you've got the lement, just do 'e.innerHTML` to retrieve the HTML.

<div><span><b>This is in bold</b></span></div>

=> <div id="wrap"><div><span><b>This is in bold</b></span></div></div>

and then:

var e=document.getElementById("wrap");
var content=e.innerHTML;

Note that outerHTML is not cross-browser compatible.


as outerHTML is IE only, use this function:

function getOuterHtml(node) {
    var parent = node.parentNode;
    var element = document.createElement(parent.tagName);
    element.appendChild(node);
    var html = element.innerHTML;
    parent.appendChild(node);
    return html;
}

creates a bogus empty element of the type parent and uses innerHTML on it and then reattaches the element back into the normal dom


You'll want something like this for it to be cross browser.

function OuterHTML(element) {
    var container = document.createElement("div");
    container.appendChild(element.cloneNode(true));

    return container.innerHTML;
}

var el = document.getElementById('foo');
el.parentNode.innerHTML;

If you want a lighter footprint, but a longer script, get the elements innerHTML and only create and clone the empty parent-

function getHTML(who,lines){
    if(!who || !who.tagName) return '';

    var txt, ax, str, el= document.createElement('div');
    el.appendChild(who.cloneNode(false));
    txt= el.innerHTML;
    ax= txt.indexOf('>')+1;
    str= txt.substring(0, ax)+who.innerHTML+ txt.substring(ax);

    el= null;
    return lines? str.replace(/> *</g,'>\n<'): str;
    //easier to read if elements are separated
}

define function outerHTML based on support for element.outerHTML:

var temp_container = document.createElement("div"); // empty div not added to DOM
if (temp_container.outerHTML){
    var outerHTML = function(el){return el.outerHTML||el.nodeValue} // e.g. textnodes do not have outerHTML
  } else { // when .outerHTML is not supported
    var outerHTML = function(el){
      var clone = el.cloneNode(true);
      temp_container.appendChild(clone);
      outerhtml = temp_container.innerHTML;
      temp_container.removeChild(clone);
      return outerhtml;
    };
  };

Examples related to javascript

need to add a class to an element How to make a variable accessible outside a function? Hide Signs that Meteor.js was Used How to create a showdown.js markdown extension Please help me convert this script to a simple image slider Highlight Anchor Links when user manually scrolls? Summing radio input values How to execute an action before close metro app WinJS javascript, for loop defines a dynamic variable name Getting all files in directory with ajax

Examples related to html

Embed ruby within URL : Middleman Blog Please help me convert this script to a simple image slider Generating a list of pages (not posts) without the index file Why there is this "clear" class before footer? Is it possible to change the content HTML5 alert messages? Getting all files in directory with ajax DevTools failed to load SourceMap: Could not load content for chrome-extension How to set width of mat-table column in angular? How to open a link in new tab using angular? ERROR Error: Uncaught (in promise), Cannot match any routes. URL Segment

Examples related to dom

How do you set the document title in React? How to find if element with specific id exists or not Cannot read property 'style' of undefined -- Uncaught Type Error adding text to an existing text element in javascript via DOM Violation Long running JavaScript task took xx ms How to get `DOM Element` in Angular 2? Angular2, what is the correct way to disable an anchor element? React.js: How to append a component on click? Detect click outside React component DOM element to corresponding vue.js component