Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to insert HTML entities with createTextNode?

Tags:

javascript

If I want to add an ascii symbol form js to a node somewhere? Tried as a TextNode, but it didn't parse it as a code:

var dropdownTriggerText = document.createTextNode('blabla ∧');
like image 330
Nik Terentyev Avatar asked Jan 06 '14 02:01

Nik Terentyev


People also ask

What is a text node HTML?

A text node encapsulates XML character content. A text node can have zero or one parent. The content of a text node can be empty. However, unless the parent of a text node is empty, the content of the text node cannot be an empty string.

What is the entity name for in HTML?

An HTML entity is a piece of text ("string") that begins with an ampersand ( & ) and ends with a semicolon ( ; ) . Entities are frequently used to display reserved characters (which would otherwise be interpreted as HTML code), and invisible characters (like non-breaking spaces).

What is textNode in Dom?

Browser support: Represents a text as a node. TextNode objects contain only text content without any HTML or XML markup. TextNode objects make it possible to insert texts into the document as nodes (appendChild, insertBefore).


2 Answers

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 &...

like image 154
dee-see Avatar answered Oct 17 '22 06:10

dee-see


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 &');
like image 38
poke Avatar answered Oct 17 '22 06:10

poke