How to insert HTML entities with createTextNode?

createTextNode is supposed to take any text input and insert it into the DOM exactly like it is. This makes it impossible to insert for example HTML elements, and HTML entities. It’s actually a feature, so you don’t need to escape these first. Instead you just operate on the DOM to insert text nodes.

So, you can actually just use the & symbol directly:

var dropdownTriggerText = document.createTextNode('blabla &');

I couldn't find an automated way to do this. So I made a function.

// render HTML as text for inserting into text nodes
function renderHTML(txt) {
  var tmpDiv = document.createElement("div"); tmpDiv.innerHTML = txt;
  return tmpDiv.innerText || tmpDiv.textContent || txt;
}

You can't create nodes with HTML entities. Your alternatives would be to use unicode values

var dropdownTriggerText = document.createTextNode('blabla \u0026');

or set innerHTML of the element. You can of course directly input &...

Tags:

Javascript