Creating a new DOM element from an HTML string using built-in DOM methods or Prototype
Asked Answered
G

30

945

I have an HTML string representing an element: '<li>text</li>'. I'd like to append it to an element in the DOM (a ul in my case). How can I do this with Prototype or with DOM methods?

(I know i could do this easily in jQuery, but unfortunately we're not using jQuery.)

Galitea answered 30/1, 2009 at 1:13 Comment(3)
Sorry, what are you trying to accomplish exactly? HTML string -> dom element?Lipscomb
It's unfortunate that these solutions are so indirect. I wish the standards committee would specify something similar like: var nodes = document.fromString("<b>Hello</b> <br>");Brunella
I had a problem with the above, because I had attributes that needed to be passed along and I didn't feel like parsing them: "<table id='5ccf9305-4b10-aec6-3c55-a6d218bfb107' class='data-table row-border display' cellspacing='0' width='100%'></table>" so, I simply used: $("<table id='5ccf9305-4b10-aec6-3c55-a6d218bfb107' class='data-table row-border display' cellspacing='0' width='100%'></table>")Enthral
L
1098

Note: most current browsers support HTML <template> elements, which provide a more reliable way of turning creating elements from strings. See Mark Amery's answer below for details.

For older browsers, and node/jsdom: (which doesn't yet support <template> elements at the time of writing), use the following method. It's the same thing the libraries use to do to get DOM elements from an HTML string (with some extra work for IE to work around bugs with its implementation of innerHTML):

function createElementFromHTML(htmlString) {
  var div = document.createElement('div');
  div.innerHTML = htmlString.trim();

  // Change this to div.childNodes to support multiple top-level nodes.
  return div.firstChild;
}

Note that unlike HTML templates this won't work for some elements that cannot legally be children of a <div>, such as <td>s.

If you're already using a library, I would recommend you stick to the library-approved method of creating elements from HTML strings:

Lipscomb answered 30/1, 2009 at 3:0 Comment(7)
How to set innerHTML to the created div using jQuery without using this unsafe innerHTML assignment (div.innerHTML = "some value")Sorry
The function name createElementFromHTML is misleading since div.firstChild returns a Node which is not a HTMLElement e.g. cannot node.setAttribute. To create an Element return div.firstElementChild from the function instead.Surround
Thank you, the <div> wrapping the HTML I added with .innerHTML was annoying me. I never thought of using .firstChild.Evanston
I'm trying to parse a SVG inside the created div and and the output is [object SVGSVGElement] while the console log gives me the correct DOM element. What am I doing wrong?Volta
Note, by the way, that this does not work for script tags. Script tags added to the DOM using innerHTML will not be executed. For those cases, better to go with var script = document.createElement('script'), and then use script.src or script.textContent depending on whether the script is inline. Then, add the script with document.body.appendChild(script).Lyly
I would use firstElementChild instead of firstChild ( see w3schools.com/jsref/prop_element_firstelementchild.asp ) , because if there is space in front or end of template, the firstChild would return empty textNodeLuca
What does div.firstChild look like for the example in the question?Delete
C
686

HTML 5 introduced the <template> element which can be used for this purpose (as now described in the WhatWG spec and MDN docs).

A <template> element is used to declare fragments of HTML that can be utilized in scripts. The element is represented in the DOM as a HTMLTemplateElement which has a .content property of DocumentFragment type, to provide access to the template's contents. This means that you can convert an HTML string to DOM elements by setting the innerHTML of a <template> element, and then reaching into the template's .content property.

Examples:

/**
 * @param {String} HTML representing a single element.
 * @param {Boolean} flag representing whether or not to trim input whitespace, defaults to true.
 * @return {Element | HTMLCollection | null}
 */
function fromHTML(html, trim = true) {
  // Process the HTML string.
  html = trim ? html.trim() : html;
  if (!html) return null;

  // Then set up a new template element.
  const template = document.createElement('template');
  template.innerHTML = html;
  const result = template.content.children;

  // Then return either an HTMLElement or HTMLCollection,
  // based on whether the input HTML had one or more roots.
  if (result.length === 1) return result[0];
  return result;
}

// Example 1: add a div to the page
const div = fromHTML('<div><span>nested</span> <span>stuff</span></div>');
document.body.append(div);

// Example 2: add a bunch of rows to an on-page table
const rows = fromHTML('<tr><td>foo</td></tr><tr><td>bar</td></tr>');
table.append(...rows);

// Example 3: add a single extra row to the same on-page table
const td = fromHTML('<td>baz</td>');
const row = document.createElement(`tr`);
row.append(td);
table.append(row);
table {
  background: #EEE;
  padding: 0.25em;
}
  
table td {
  border: 1px solid grey;
  padding: 0 0.5em;
}
<table id="table"></table>

Note that similar approaches that use a different container element such as a div don't quite work. HTML has restrictions on what element types are allowed to exist inside which other element types; for instance, you can't put a td as a direct child of a div. This causes these elements to vanish if you try to set the innerHTML of a div to contain them. Since <template>s have no such restrictions on their content, this shortcoming doesn't apply when using a template.

This approach was previously not always possible due to IE not having support for <template>, but Microsoft fully killed off the Internet Explorer family of browsers in June of 2022, with Windows updates pushed out to even prevent folks from (re)installing it, so except in the rare few cases where you find yourself writing web content for dead browsers, this approach will work for you.

Caseose answered 13/2, 2016 at 21:25 Comment(13)
This is an effective approach and very clean; however, (at least in Chrome 50) this breaks script tag handling. In other words, using this method to create a script tag and then appending it to the document (body or head) doesn't result in the tag being evaluated and hence prevents the script from being executed. (This may be by design if evaluation happens on attach; I couldn't say for sure.)Vicar
LOVELY! you can even query for elements by doing something like: template.content.querySelector("img");Pianist
I don't see innerHTML defined as a property of DOM fragment objects (from <template>.content) on MDN: developer.mozilla.org/en-US/docs/Web/API/DocumentFragmentChe
@Che indeed not, since there is no such property. You've misread my answer; I set the innerHTML of the template itself (which is an Element), not its .content (which is a DocumentFragment).Caseose
There is one problem with it. If you have a tag in there with spaces inside(!) at start or end, they will be removed! Don't get me wrong, this is not about the spaces removed by html.trim but by inner parsing of innerHTML setting. In my case it removes important spaces being part of a textNode. :-(Simper
template.content.firstElementChild can be used instead of stripping the html.Kilkenny
How to combine this two functions to work with any string type (single element / number of siblings)?Touchdown
@Touchdown I guess you could use htmlToElements but change the final line to return template.content.childNodes.length == 1 ? template.content.firstChild : template.content.childNodes;, but I wouldn't recommend it; it seems weird to me to have a function that usually returns a collection but sometimes returns a single item.Caseose
Unfortunately in Safari (iOS and Desktop v15.5) this stops videos fromautoplaying, and makes a.origin for any relative URLs the string "null" (!!!). The createElement('div') approach doesn't have those issues.Wharfinger
Also here as a one-liner: Object.assign(document.createElement('template'),{innerHTML: html.trim()}).content.firstChildMeatman
.firstChild returns a ChildNode not an ElementShrunken
@BartLouwers That ChildNode will be an Element as long as the HTML you pass to the function represents an element, as the function docs instruct that it should. You're right that the function as written doesn't actually enforce that, though, and that htmlToElement("plain text with no tags") will return a CharacterData instead. Either renaming the function to htmlToNode or adding some validation that throws an error if !(template.content.firstChild instanceof Element) might be a reasonable fix for this, depending upon which approach to handling non-Element nodes you'd prefer!Caseose
Note that as long as you inject scripts made this way into the head, on their own, they will run just fine. E.g. <template id="test"><script>console.log(`cool`);</script></template> combined with document.head.append(test.content.cloneNode(true)); works perfectly fine (but note the use of cloneNode, because you should never relocate a template's node by giving it a new parent, you should create a copy and place that, instead).Hematology
R
247

Use insertAdjacentHTML(). It works with all current browsers, even with IE11.

var mylist = document.getElementById('mylist');
mylist.insertAdjacentHTML('beforeend', '<li>third</li>');
<ul id="mylist">
 <li>first</li>
 <li>second</li>
</ul>
Radioscopy answered 28/10, 2017 at 22:3 Comment(8)
First, insertAdjacentHTML works with all browsers since IE 4.0.Disreputable
Second, it's great! A big plus compared to innerHTML += ... is that references to previous elements is still intact using this method.Disreputable
Third, possible values for the first argument is: beforebegin, afterbegin, beforeend, afterend. See the MDN article.Disreputable
Too bad it doesn't return the inserted HTML as an elementMelanymelaphyre
This has fantastic browser support and is entirely straightforward. There's no odd creating a dummy element just to get its child Node.Pasquil
This answer should be the one, it worked perfect!Bega
Kudos for this answer, I have been testing and searching like crazy to replace the jQuery function.Anathema
@DylanReile: right, now you just have to query them all back if you need to manipulate them in any way at all. I imagine a template costs about nothing and it's not a dummy - it's parsing your html.Esme
I
51

No need for any tweak, you got a native API:

const toNodes = html =>
    new DOMParser().parseFromString(html, 'text/html').body.childNodes[0]
Ichabod answered 24/2, 2017 at 21:48 Comment(5)
This suffers from the same major drawback as the accepted answer - it will mangle HTML like <td>text</td>. This is because DOMParser is trying to parse a full HTML document, and not all elements are valid as root elements of a document.Caseose
-1 because this is a duplicate of an earlier answer that explicitly pointed out the drawback mentioned in my comment above.Caseose
@MarkAmery it doesn't matter. this answer and syntax is shaped as what we are used to see today. It's never a bad duplicate if it shows a more modern way to write something.Sihunn
Can't this be modified to work with fragments by wrapping in an HTML root element and plucking the firstChild?Nippon
Sure, but then you've kind of negated any reason for using DOMParser in the first place. Just create a template, set the innerHTML property, and cloneNode the thing. And then you can't get bit by typoing a mimetype and spending an hour trying to figure out why things don't work because you keep glossing over 'text/hmtl'.Hematology
I
41

For certain html fragments like <td>test</td>, div.innerHTML, DOMParser.parseFromString and range.createContextualFragment (without the right context) solutions mentioned in other answers here, won't create the <td> element.

jQuery.parseHTML() handles them properly (I extracted jQuery 2's parseHTML function into an independent function that can be used in non-jquery codebases).

If you are only supporting Edge 13+, it is simpler to just use the HTML5 template tag:

function parseHTML(html) {
    var t = document.createElement('template');
    t.innerHTML = html;
    return t.content;
}

var documentFragment = parseHTML('<td>Test</td>');
Inescutcheon answered 17/12, 2015 at 11:42 Comment(0)
G
34

Newer DOM implementations have range.createContextualFragment, which does what you want in a framework-independent way.

It's widely supported. To be sure though, check its compatibility down in the same MDN link, as it will be changing. As of May 2017 this is it:

Feature         Chrome   Edge   Firefox(Gecko)  Internet Explorer   Opera   Safari
Basic support   (Yes)    (Yes)  (Yes)           11                  15.0    9.1.2
Given answered 6/9, 2011 at 21:53 Comment(2)
Note that this has similar drawbacks to setting the innerHTML of a div; certain elements, like tds, will be ignored and not appear in the resulting fragment.Caseose
"There are reports that desktop Safari did at one point support Range.createContextualFragment(), but it is not supported at least in Safari 9.0 and 9.1." (MDN link in the answer)Brimstone
A
17

Heres a simple way to do it:

String.prototype.toDOM=function(){
  var d=document
     ,i
     ,a=d.createElement("div")
     ,b=d.createDocumentFragment();
  a.innerHTML=this;
  while(i=a.firstChild)b.appendChild(i);
  return b;
};

var foo="<img src='//placekitten.com/100/100'>foo<i>bar</i>".toDOM();
document.body.appendChild(foo);
Alves answered 3/5, 2013 at 0:2 Comment(1)
@MarkAmery the difference here is that he uses a fragment to allow multiple root element be appended in the DOM, which is an added benefit. If only William did mention that is his answer...Bejewel
F
16

You can create valid DOM nodes from a string using:

document.createRange().createContextualFragment()

The following example adds a button element in the page taking the markup from a string:

let html = '<button type="button">Click Me!</button>';
let fragmentFromString = function (strHTML) {
  return document.createRange().createContextualFragment(strHTML);
}
let fragment = fragmentFromString(html);
document.body.appendChild(fragment);
Felspar answered 28/2, 2017 at 14:31 Comment(3)
Even though this creates a DocumentFragment object, it still - to my great surprise - suffers from the same defect as the accepted answer: if you do document.createRange().createContextualFragment('<td>bla</td>'), you get a fragment that just contains the text 'bla' without the <td> element. Or at least, that's what I observe in Chrome 63; I haven't delved into the spec to figure out whether it's the correct behavior or not.Caseose
A slightly shorter version to the above is also new Range().createContextualFragment(htmlString)Meatman
IIRC there have historically been DOM elements that can't exist as nodes on their own, whether in fragments or not. They're only valid as descendants of other elements, so if you try to create them on their own, it doesn't work.Execrable
C
11

I am using this method (Works in IE9+), although it will not parse <td> or some other invalid direct childs of body:

function stringToEl(string) {
    var parser = new DOMParser(),
        content = 'text/html',
        DOM = parser.parseFromString(string, content);

    // return element
    return DOM.body.childNodes[0];
}

stringToEl('<li>text</li>'); //OUTPUT: <li>text</li>
Catarinacatarrh answered 8/6, 2016 at 12:39 Comment(0)
B
11

I added a Document prototype that creates an element from string:

Document.prototype.createElementFromString = function (str) {
   const element = new DOMParser().parseFromString(str, 'text/html');
   const child = element.documentElement.querySelector('body').firstChild;
   return child;
};

Usage:

document.createElementFromString("<h1>Hello World!</h1>");
Blintze answered 20/8, 2017 at 17:24 Comment(2)
Note that - as pointed out elsewhere on this page - this won't work for tds.Caseose
Parsing “<table><tr>” + tdRowArr.join(“”) + “</tr></table” and then moving the TD nodes shouldn’t be very hard, similar to how he extracts the actual nodes from the body tag aboveReform
C
8

Why don't do with native js?

    var s="<span class='text-muted' style='font-size:.75em; position:absolute; bottom:3px; left:30px'>From <strong>Dan's Tools</strong></span>"
    var e=document.createElement('div')
    var r=document.createRange();
    r.selectNodeContents(e)
    var f=r.createContextualFragment(s);
    e.appendChild(f);
    e = e.firstElementChild;
Conscience answered 22/5, 2020 at 19:51 Comment(4)
Great answer by farDynameter
amazing!! Then one can easily use node.appendChild(e)Conventionality
That moment when you realize that the native solution is the simplest one-->priceless ^_^Opinionated
out of interest, why would this be favoured over insertAdjacentHTML?Myth
M
6

Answer

  • Create a Template
  • Set the Template's innerHTML to your string .trim()
  • Create an Array of Template's children
  • Return children, child, or

function toElement(s='',c,t=document.createElement('template'),l='length'){
t.innerHTML=s.trim();c=[...t.content.childNodes];return c[l]>1?c:c[0]||'';}



console.log(toElement());
console.log(toElement(''));
console.log(toElement('    '));
console.log(toElement('<td>With td</td>'));
console.log(toElement('<tr><td>With t</td></tr>'));
console.log(toElement('<tr><td>foo</td></tr><tr><td>bar</td></tr>'));
console.log(toElement('<div><span>nested</span> <span>stuff</span></div>'));
Milesmilesian answered 12/7, 2020 at 22:2 Comment(0)
B
5

Solution - works with all browsers since IE 4.0

var htmlString = `<body><header class="text-1">Hello World</header><div id="table"><!--TABLE HERE--></div></body>`;
var tableString = `<table class="table"><thead><tr><th>th cell</th></tr></thead><tbody><tr><td>td cell</td></tr></tbody></table>`;


var doc = document.implementation.createHTMLDocument();
    doc.open();
    doc.write(htmlString);
    doc.getElementById('table').insertAdjacentHTML('beforeend', tableString);
    doc.close();

console.log(doc);

Or you can use DOMParser

var doc = (new DOMParser).parseFromString(htmlString, "text/html");
    doc.getElementById('table').insertAdjacentHTML('beforeend', tableString);

console.log(doc);
Bronchiectasis answered 11/8, 2022 at 10:43 Comment(0)
P
4

Here's how to do it with PrototypeJS (as originally requested by the OP 12 years ago):

HTML:

<ul id="mylist"></ul>

JS:

$('mylist').insert('<li>text</li>');

Note that this is not jQuery!

Plesiosaur answered 19/2, 2009 at 15:13 Comment(3)
Is this jQuery? or JS?Shrew
@JuanHurtado this is using PrototypeJs as OP requested almost 11 years ago ;)Plesiosaur
@PabloBorowicz Oops you're correct. My mind automatically went to the "built in dom methods" and I missed the prototype part.Borate
J
4

HTML5 & ES6

<template>

Demo

"use strict";

/**
 *
 * @author xgqfrms
 * @license MIT
 * @copyright xgqfrms
 * @description HTML5 Template
 * @augments
 * @example
 *
 */

/*

<template>
    <h2>Flower</h2>
    <img src="https://www.w3schools.com/tags/img_white_flower.jpg">
</template>


<template>
    <div class="myClass">I like: </div>
</template>

*/

const showContent = () => {
    // let temp = document.getElementsByTagName("template")[0],
    let temp = document.querySelector(`[data-tempalte="tempalte-img"]`),
        clone = temp.content.cloneNode(true);
    document.body.appendChild(clone);
};

const templateGenerator = (datas = [], debug = false) => {
    let result = ``;
    // let temp = document.getElementsByTagName("template")[1],
    let temp = document.querySelector(`[data-tempalte="tempalte-links"]`),
        item = temp.content.querySelector("div");
    for (let i = 0; i < datas.length; i++) {
        let a = document.importNode(item, true);
        a.textContent += datas[i];
        document.body.appendChild(a);
    }
    return result;
};

const arr = ["Audi", "BMW", "Ford", "Honda", "Jaguar", "Nissan"];

if (document.createElement("template").content) {
    console.log("YES! The browser supports the template element");
    templateGenerator(arr);
    setTimeout(() => {
        showContent();
    }, 0);
} else {
    console.error("No! The browser does not support the template element");
}
@charset "UTf-8";

/* test.css */

:root {
    --cololr: #000;
    --default-cololr: #fff;
    --new-cololr: #0f0;
}

[data-class="links"] {
    color: white;
    background-color: DodgerBlue;
    padding: 20px;
    text-align: center;
    margin: 10px;
}
<!DOCTYPE html>
<html lang="zh-Hans">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Template Test</title>
    <!--[if lt IE 9]>
        <script src="https://cdnjs.cloudflare.com/ajax/libs/html5shiv/3.7.3/html5shiv.js"></script>
    <![endif]-->
</head>

<body>
    <section>
        <h1>Template Test</h1>
    </section>
    <template data-tempalte="tempalte-img">
        <h3>Flower Image</h3>
        <img src="https://www.w3schools.com/tags/img_white_flower.jpg">
    </template>
    <template data-tempalte="tempalte-links">
        <h3>links</h3>
        <div data-class="links">I like: </div>
    </template>
    <!-- js -->
</body>

</html>
Jolynjolynn answered 28/5, 2018 at 11:45 Comment(0)
C
3

Late but just as a note;

It's possible to add a trivial element to target element as a container and remove it after using.

// Tested on chrome 23.0, firefox 18.0, ie 7-8-9 and opera 12.11.

<div id="div"></div>

<script>
window.onload = function() {
    var foo, targetElement = document.getElementById('div')
    foo = document.createElement('foo')
    foo.innerHTML = '<a href="#" target="_self">Text of A 1.</a> '+
                    '<a href="#" onclick="return !!alert(this.innerHTML)">Text of <b>A 2</b>.</a> '+
                    '<hr size="1" />'
    // Append 'foo' element to target element
    targetElement.appendChild(foo)

    // Add event
    foo.firstChild.onclick = function() { return !!alert(this.target) }

    while (foo.firstChild) {
        // Also removes child nodes from 'foo'
        targetElement.insertBefore(foo.firstChild, foo)
    }
    // Remove 'foo' element from target element
    targetElement.removeChild(foo)
}
</script>
Cullan answered 13/12, 2012 at 12:39 Comment(0)
U
3

Fastest solution to render DOM from string:

let render = (relEl, tpl, parse = true) => {
  if (!relEl) return;
  const range = document.createRange();
  range.selectNode(relEl);
  const child = range.createContextualFragment(tpl);
  return parse ? relEl.appendChild(child) : {relEl, el};
};

And here u can check performance for DOM manipulation React vs native JS

Now u can simply use:

let element = render(document.body, `
<div style="font-size:120%;line-height:140%">
  <p class="bold">New DOM</p>
</div>
`);

And of course in near future u use references from memory cause var "element" is your new created DOM in your document.

And remember "innerHTML=" is very slow :/

Unfeeling answered 16/1, 2020 at 12:18 Comment(1)
great answer, thanks. don't suppose you've any more links to share on the topic (like going deeper into why it's faster?)Myth
V
2

Here's my code, and it works:

function parseTableHtml(s) { // s is string
    var div = document.createElement('table');
    div.innerHTML = s;

    var tr = div.getElementsByTagName('tr');
    // ...
}
Ventage answered 21/5, 2011 at 7:40 Comment(1)
Fails if the element to be created is itself a table.Caseose
C
2

I have searched a lot for this myself and came across this solution which is neat.

const stringToHTML = (str) => {
    var parser = new DOMParser();
    var doc = parser.parseFromString(str, 'text/html');
    return doc.body;
};

String that I wanted to convert:

'<iframe src="https://player.vimeo.com/video/578680903?h=ea840f9223&amp;app_id=122963" width="640" height="360" frameborder="0" allow="autoplay; fullscreen; picture-in-picture" allowfullscreen title="Total Body Balance"></iframe>'

The result:

<body><iframe src="https://player.vimeo.com/video/578680903?h=ea840f9223&amp;app_id=122963" width="640" height="360" frameborder="0" allow="autoplay; fullscreen; picture-in-picture" allowfullscreen="" title="Total Body Balance"></iframe></body>
Concision answered 6/10, 2021 at 11:38 Comment(1)
Just me that finds it a bit funny to init a domparser, a domdocument and so on.. just to generate a single node where most options are just set on a createElement(iframe)..? Not the most compelling use case.. ;)Reform
K
1

For the heck of it I thought I'd share this over complicated but yet simple approach I came up with... Maybe someone will find something useful.

/*Creates a new element - By Jamin Szczesny*/
function _new(args){
    ele = document.createElement(args.node);
    delete args.node;
    for(x in args){ 
        if(typeof ele[x]==='string'){
            ele[x] = args[x];
        }else{
            ele.setAttribute(x, args[x]);
        }
    }
    return ele;
}

/*You would 'simply' use it like this*/

$('body')[0].appendChild(_new({
    node:'div',
    id:'my-div',
    style:'position:absolute; left:100px; top:100px;'+
          'width:100px; height:100px; border:2px solid red;'+
          'cursor:pointer; background-color:HoneyDew',
    innerHTML:'My newly created div element!',
    value:'for example only',
    onclick:"alert('yay')"
}));
Kirovograd answered 21/9, 2013 at 3:47 Comment(1)
For the record I gave this code a go - IT IS BLOODY SUPERB. I think is going to become my go-to way of dynamically creating html from json - huge thanks mate!!Alex
O
1

Visit https://www.codegrepper.com/code-examples/javascript/convert+a+string+to+html+element+in+js

const stringToHtml = function (str) {
    var parser = new DOMParser();
    var doc = parser.parseFromString(str, 'text/html');
    return doc.body;
}
Overrefinement answered 3/3, 2022 at 16:11 Comment(0)
G
1

What about using outerHTML ?

*element*.appendChild( document.createElement('li')).outerHTML= '<li>text</li>' ;

The parameter for createElement doesn't need to match the element type specified in your string, but it does need to be a legal child of element

*element*.appendChild( document.createElement('a')).outerHTML= '<li>text</li>' ;

works just as well

Granular answered 1/5, 2023 at 0:4 Comment(0)
A
-1
function domify (str) {
  var el = document.createElement('div');
  el.innerHTML = str;

  var frag = document.createDocumentFragment();
  return frag.appendChild(el.removeChild(el.firstChild));
}

var str = "<div class='foo'>foo</div>";
domify(str);
Aluminum answered 8/2, 2016 at 10:59 Comment(0)
S
-1

I've linked from this article.( Converting HTML string into DOM elements? )

For me, I want to find a way to convert a string into an HTML element. If you also have this need, you can try the following

const frag = document.createRange().createContextualFragment(
`<a href="/link.js">js</a> 
 <a>go</a>
`
) 
const aCollection = frag.querySelectorAll("a")
for (let [key, a] of Object.entries(aCollection)) {
  console.log(a.getAttribute("href"), a.textContent)
}
Sanctitude answered 26/4, 2021 at 9:41 Comment(0)
G
-1

Example with latest JS:

<template id="woof-sd-feature-box">
<div class="woof-sd-feature-box" data-key="__KEY__" data-title="__TITLE__" data-data="__OPTIONS__">
    <h4>__TITLE__</h4>
    <div class="woof-sd-form-item-anchor">
        <img src="img/move.png" alt="">
    </div>
</div>

</template>

<script>
create(example_object) {
        let html = document.getElementById('woof-sd-feature-box').innerHTML;
        html = html.replaceAll('__KEY__', example_object.dataset.key);
        html = html.replaceAll('__TITLE__', example_object.dataset.title);
        html = html.replaceAll('__OPTIONS__', example_object.dataset.data);
        //convertion HTML to DOM element and prepending it into another element
        const dom = (new DOMParser()).parseFromString(html, "text/html");
        this.container.prepend(dom.querySelector('.woof-sd-feature-box'));
    }
</script>
Grijalva answered 21/1, 2022 at 14:57 Comment(0)
A
-2

You can use the following function to convert the text "HTML" to the element

function htmlToElement(html)
{
  var element = document.createElement('div');
  element.innerHTML = html;
  return(element);
}
var html="<li>text and html</li>";
var e=htmlToElement(html);
Aker answered 11/7, 2017 at 6:5 Comment(1)
-1; this is the same technique as proposed in the accepted answer and has the same drawbacks - notably, not working for tds.Caseose
W
-3

Here is working code for me

I wanted to convert 'Text' string to HTML element

var diva = UWA.createElement('div');
diva.innerHTML = '<a href="http://wwww.example.com">Text</a>';
var aelement = diva.firstChild;
Waterlog answered 8/1, 2018 at 10:23 Comment(1)
What is wwww?Astromancy
S
-3

var msg = "test" jQuery.parseHTML(msg)

Shippee answered 22/5, 2019 at 10:11 Comment(1)
Thank you for this code snippet, which might provide some limited, immediate help. A proper explanation would greatly improve its long-term value by showing why this is a good solution to the problem and would make it more useful to future readers with other, similar questions. Please edit your answer to add some explanation, including the assumptions you’ve made.Dullard
D
-4
var jtag = $j.li({ child:'text' }); // Represents: <li>text</li>
var htmlContent = $('mylist').html();
$('mylist').html(htmlContent + jtag.html());

Use jnerator

Dinsdale answered 25/9, 2012 at 0:39 Comment(0)
O
-9

This will work too:

$('<li>').text('hello').appendTo('#mylist');

It feels more like a jquery way with the chained function calls.

Oratorian answered 11/4, 2012 at 22:2 Comment(2)
Does it feel like jQuery because it is jQuery?Nea
That last line is just hilarious!Lotic

© 2022 - 2024 — McMap. All rights reserved.