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
Run code snippetEdit code snippet Hide Results Copy to answer Expand
Answer from maerics on Stack OverflowYou 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
Run code snippetEdit code snippet Hide Results Copy to answer Expand
You typically create a temporary parent element to which you can write the innerHTML, then extract the contents:
var wrapper= document.createElement('div');
wrapper.innerHTML= '<div><a href="#"></a><span></span></div>';
var div= wrapper.firstChild;
If the element whose outer-HTML you've got is a simple <div> as here, this is easy. If it might be something else that can't go just anywhere, you might have more problems. For example if it were a <li>, you'd have to have the parent wrapper be a <ul>.
But IE can't write innerHTML on elements like <tr> so if you had a <td> you'd have to wrap the whole HTML string in <table><tbody><tr>...</tr></tbody></table>, write that to innerHTML and extricate the actual <td> you wanted from a couple of levels down.
javascript - Convert a string to html tags - Salesforce Stack Exchange
Convert string to HTML element using JavaScript or jQuery - Stack Overflow
Parse html elements which are contained in a string
*Best Practice* creating and writing the html with JS
split the initial string on the comma, then map over the resulting array. On each iteration of map you can then split on the colon, and return a HTML string. You just need to make sure you join the array that map returns into a new string before you add it to the DOM.
const str = 'i1:1,i3:5,i2:5';
const result = str.split(',').map(el => {
const [key, value] = el.split(':');
return `<li id="${key}" value="${value}">${value}</li>`;
}).join('');
const ol = document.querySelector('ol');
ol.insertAdjacentHTML('beforeend', `<ul>${result}</ul>`);
<ol />
Run code snippetEdit code snippet Hide Results Copy to answer Expand
Additional documentation
Destructuring assignment
Template literals
insertAdjacentHTML
I believe that my simple solution using method forEach() and method split() will not be superfluous, which will split the string into an id and a value taken from an array of similar data.
let ul = document.createElement("ul");
document.body.appendChild(ul);
["i1:1", "i3:5", "i2:5"].forEach(function (li) {
let id_value = li.split(":");
ul.innerHTML += "<li id=" + id_value[0] + ">" + id_value[1] + "</li>";
});
console.log(ul.outerHTML);
Run code snippetEdit code snippet Hide Results Copy to answer Expand