How to Convert a Htmlelement to a String

How to convert a HTMLElement to a string

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

Converting HTML element to string in JavaScript / JQuery

You can do this:

var $html = $('<iframe width="854" height="480" src="http://www.youtube.com/embed/gYKqrjq5IjU?feature=oembed" frameborder="0" allowfullscreen></iframe>');    var str = $html.prop('outerHTML');console.log(str);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>

JavaScript convert string into HTML element

Use the innerHTML property of an element.

E.g.

let element = document.getElementById('myElement');

element.innerHTML = "<i class="fas fa-star"></i><i class="fas fa-star"></i><i class="fas fa-star"></i><i class="fas fa-star"></i><i class="fas fa-star"></i>"

Converting HTML string into DOM elements?

You can use a DOMParser, like so:

var xmlString = "<div id='foo'><a href='#'>Link</a><span></span></div>";var doc = new DOMParser().parseFromString(xmlString, "text/xml");console.log(doc.firstChild.innerHTML); // => <a href="#">Link...console.log(doc.firstChild.firstChild.innerHTML); // => Link

How to convert the html object to string type?

I believe you want to use Element.outerHTML:

console.log(content.outerHTML)

convert htmlelement to string for comparison javascript

The line:

var click = (e && e.target) || (event && event.srcElement);

is not getting the id rather the element itself, use getAttribute to get the id instead.

var id = click.getAttribute('id');
alert(id);

Or simply:

var id = click.id;
alert(id);

So your condition now becomes:

if (id == 'about') {do something}

and

if (id == document.getElementById('help')) {do something}


Related Topics



Leave a reply



Submit