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.
The element outerHTML
property (note: supported by Firefox after version 11) returns the HTML of the entire element.
<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).
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;
}
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);
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With