How do i turn a html element into a string?

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,50210 gold badges45 silver badges61 bronze badges

asked Mar 19, 2010 at 2:21

1

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

Example

Hello world.

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

answered Mar 19, 2010 at 2:32

gpmcadamgpmcadam

5,8862 gold badges30 silver badges35 bronze badges

3

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;
}

answered Mar 19, 2010 at 3:04

kennebeckennebec

100k31 gold badges104 silver badges126 bronze badges

2

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

const htmlTemplate = ``;

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

const doctype = '';
const html = doc.documentElement.outerHTML;

console.log(doctype + html);

answered Aug 6, 2020 at 18:53

topvovatopvova

411 silver badge6 bronze badges

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 = "";
alert(closeTag);

answered Mar 19, 2010 at 2:30

How do i turn a html element into a string?

3

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 :)

answered May 19, 2017 at 10:12

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

@ViewChild('myHTML', {static: false}) _html: ElementRef;
this._html.nativeElement;

answered Dec 11, 2019 at 13:00

JnrJnr

1,2902 gold badges19 silver badges32 bronze badges

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  in bold

How do i turn a html element into a string?

FLAW

1871 silver badge11 bronze badges

answered May 8, 2013 at 15:39

MiguelMiguel

3,0732 gold badges29 silver badges28 bronze badges

How do I convert HTML tags to text?

Below are several methods for converting, or saving, an HTML web page as a text document..
Click the File tab again, then click the Save as option..
In the Save as type drop-down list, select the Plain Text (*. txt) option. ... .
Click the Save button to save as a text document..

What is an HTML string?

Unlike most HTML parsers which generate tree structures, HTMLString generates a string of characters each with its own set of tags. This flat structure makes it easy to manipulate ranges (for example - text selected by a user) as each character is independent and doesn't rely on a hierarchical tag structure.

How do you turn an object into a string in JavaScript?

Stringify a JavaScript Object Use the JavaScript function JSON. stringify() to convert it into a string. const myJSON = JSON. stringify(obj);

How do you add a string in HTML?

Using the innerHTML attribute: To append using the innerHTML attribute, first select the element (div) where you want to append the code. Then, add the code enclosed as strings using the += operator on innerHTML.