Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

javascript: create HTMLElement from string

Tags:

javascript

I want to create HTMLElement from string by javasacript, like this

element = createHTMLElement('<table class="list"><tr><td><a href="xxx">title</a></td></tr></table>')
element.addEventListener(...)
parent.appendChild(element)

and I do not want to use jQuery

like image 488
guilin 桂林 Avatar asked Dec 04 '10 15:12

guilin 桂林


People also ask

How do you make a DOM String?

The createElement() method is used for creating elements within the DOM. It accepts two parameters, a tagName which is a string that defines the type of element to create, and an optional options object that can be used to modify how the element is created.

How do you make a String in HTML?

The simplest way to do this is to create an element, insert the string into with innerHTML , then return the element. /** * Convert a template string into HTML DOM nodes * @param {String} str The template string * @return {Node} The template HTML */ var stringToHTML = function (str) { var dom = document.

What is Javascript createElement?

createElement() method creates the HTML element specified by tagName, or an HTMLUnknownElement if tagName isn't recognized.


3 Answers

You can create some dummy outer element:

  var div = document.createElement('DIV');

and then:

  div.innerHTML = '<table class="list"><tr><td><a href="xxx">title</a></td></tr></table>'

and then extract it from childNodes:

  div.firstChild

innerHTML is a Microsoft extension, but one universally supported on all modern browsers.

Of course you can form a simple function which does what you want from these snippets.

like image 50
EFraim Avatar answered Sep 17 '22 15:09

EFraim


You can also append an element using the parent's innerHTML property like this:

        this.parentEl.innerHTML += `
<a-sphere 
  class="a-sim-body"
  dynamic-body 
  position="1 1 1" 
  radius="1" 
  color="blue">
</a-sphere>`
like image 35
Michael Cole Avatar answered Sep 18 '22 15:09

Michael Cole


Use caution with the top answer as pasqal suggests.

The problem is that .firstChild might not always be what you expect. In my case, I had a single root node (so I thought), but with leading whitespace. Here's a minimal example of my failing code:

const el = document.createElement("div");
el.innerHTML = `
  <p>foo</p>
`;
el.firstChild.classList.add("foo");

The issue is that .firstChild is really a .nodeType === Node.TEXT_NODE:

const el = document.createElement("div");
el.innerHTML = `
  <p>foo</p>
`;
console.log(el.childNodes[0].nodeType === Node.TEXT_NODE);
console.log(el.childNodes[0].textContent);
console.log(el.childNodes[1].nodeType === Node.TEXT_NODE);
console.log(el.childNodes[1].textContent);

How to deal with this is use-case dependent, but you could glue together the non-text nodes with .filter or if you're sure you have one root, as was my case, you can use .find:

const el = document.createElement("div");
el.innerHTML = `
  <p>foo</p>
`;
const root = [...el.childNodes].find(e => e.nodeType !== Node.TEXT_NODE)
console.log(root);
root.classList.add("foo"); // works now
like image 21
ggorlen Avatar answered Sep 19 '22 15:09

ggorlen