122

I am going to create an XML element in JavaScript to exchange data with server side. I found I can do it with document.createElement. But I do not know how to convert it to string. Is there any API in browser to make it easier? Or is there any JS library including this API?

EDIT: I found that browser API XMLSerializer, it should be the right way to serialize to string.

montrealist
  • 5,593
  • 12
  • 46
  • 68
xiao 啸
  • 6,350
  • 9
  • 40
  • 51
  • possible duplicate of [Creating a new DOM element from an HTML string using built-in DOM methods or prototype](http://stackoverflow.com/questions/494143/creating-a-new-dom-element-from-an-html-string-using-built-in-dom-methods-or-pro) – T.Todua Jun 21 '15 at 11:07

8 Answers8

215

The element outerHTML property (note: supported by Firefox after version 11) returns the HTML of the entire element.

Example

<div id="new-element-1">Hello world.</div>

<script type="text/javascript"><!--

var element = document.getElementById("new-element-1");
var elementHtml = element.outerHTML;
// <div id="new-element-1">Hello world.</div>

--></script>

Similarly, you can use innerHTML to get the HTML contained within a given element, or innerText to get the text inside an element (sans HTML markup).

See Also

  1. outerHTML - Javascript Property
  2. Javascript Reference - Elements
Community
  • 1
  • 1
gpmcadam
  • 6,346
  • 2
  • 33
  • 37
  • 1
    But it seems I cannot get the inside text with the property outerHTML. I think what I really want is the HTML markup. – xiao 啸 Mar 19 '10 at 02:34
  • 3
    outerHTML is supported in FF from v11 https://developer.mozilla.org/en-US/docs/Web/API/element.outerHTML – llamerr Aug 08 '13 at 10:07
  • outerHTML is supported in almost all modern browsers: https://caniuse.com/#feat=mdn-api_element_outerhtml – Williams A. Dec 09 '19 at 11:10
48

You can get the 'outer-html' by cloning the element, adding it to an empty,'offstage' container, and reading the container's innerHTML.

This example takes an optional second parameter.

Call document.getHTML(element, true) to include the element's descendents.

document.getHTML= function(who, deep){
    if(!who || !who.tagName) return '';
    var txt, ax, el= document.createElement("div");
    el.appendChild(who.cloneNode(false));
    txt= el.innerHTML;
    if(deep){
        ax= txt.indexOf('>')+1;
        txt= txt.substring(0, ax)+who.innerHTML+ txt.substring(ax);
    }
    el= null;
    return txt;
}
kennebec
  • 102,654
  • 32
  • 106
  • 127
6

Suppose your element is entire [object HTMLDocument]. You can convert it to a String this way:

const htmlTemplate = `<!DOCTYPE html><html lang="en"><head></head><body></body></html>`;

const domparser = new DOMParser();
const doc = domparser.parseFromString(htmlTemplate, "text/html"); // [object HTMLDocument]

const doctype = '<!DOCTYPE html>';
const html = doc.documentElement.outerHTML;

console.log(doctype + html);
topvova
  • 71
  • 2
  • 6
3

There's a tagName property, and a attributes property as well:

var element = document.getElementById("wtv");
var openTag = "<"+element.tagName;
for (var i = 0; i < element.attributes.length; i++) {
    var attrib = element.attributes[i];
    openTag += " "+attrib.name + "=" + attrib.value;
}
openTag += ">";
alert(openTag);

See also How to iterate through all attributes in an HTML element? (I did!)

To get the contents between the open and close tags you could probably use innerHTML if you don't want to iterate over all the child elements...

alert(element.innerHTML);

... and then get the close tag again with tagName.

var closeTag = "</"+element.tagName+">";
alert(closeTag);
Community
  • 1
  • 1
Richard JP Le Guen
  • 28,364
  • 7
  • 89
  • 119
  • 2
    I am afraid it takes sometimes to write the code which gets the entire markup. – xiao 啸 Mar 19 '10 at 02:38
  • If its XML it should all be in one root node, yes? If so, then you only have to do this for the root node - innerHTML is supported on all major browsers, and will give you the X(H)TML nested in the root node. (ie everything!) – Richard JP Le Guen Mar 19 '10 at 02:40
  • 2
    Why bother looping over the element's attributes and building a string 'tag' from it? Just wrap the element in ANOTHER element, and take the innerHTML of that new parent element. Voila, instant workaround for outerHTML. – Marc B Mar 19 '10 at 03:34
1

The most easy way to do is copy innerHTML of that element to tmp variable and make it empty, then append new element, and after that copy back tmp variable to it. Here is an example I used to add jquery script to top of head.

var imported = document.createElement('script');
imported.src = 'http://code.jquery.com/jquery-1.7.1.js';
var tmpHead = document.head.innerHTML;
document.head.innerHTML = "";
document.head.append(imported);
document.head.innerHTML += tmpHead;

That simple :)

1

The easiest way that I could find was to use Element.outerHTML.toString()

const element = document.createElement('div');
element.innerHTML="Hello world !";
console.log(element.outerHTML.toString());

it will returns :

"<div>Hello world !</div>"
Mustafa Poya
  • 2,615
  • 5
  • 22
  • 36
Loutag
  • 21
  • 1
  • 6
0

This might not apply to everyone's case, but when extracting from xml I had this problem, which I solved with this.

function grab_xml(what){
var return_xml =null;
    $.ajax({
                type: "GET",
                url: what,
                success:function(xml){return_xml =xml;},
        async:   false
        });
return(return_xml);
}

then get the xml:

var sector_xml=grab_xml("p/sector.xml");
var tt=$(sector_xml).find("pt");

Then I then made this function to extract xml line , when i need to read from an XML file, containing html tags.

    function extract_xml_line(who){
    var tmp = document.createElement("div");
    tmp.appendChild(who[0]);
    var tmp=$(tmp.innerHTML).html();
    return(tmp);
}

and now to conclude:

var str_of_html= extract_xml_line(tt.find("intro")); //outputs the intro tag and whats inside it: helllo  <b>in bold</b>
FLAW
  • 307
  • 2
  • 12
Miguel
  • 3,349
  • 2
  • 32
  • 28
0

I was using Angular, and needed the same thing, and landed at this post.

@ViewChild('myHTML', {static: false}) _html: ElementRef;
this._html.nativeElement;
Jnr
  • 1,504
  • 2
  • 21
  • 36