Editing a TextNode
object
Updated:
What is a TextNode
object?
**Text
inherits from CharacterData
which in turn inherits from Node
. **
- It only contains text content without any HTML or XML markup, making it possible to insert texts into the document as nodes.
- It is the
textContent
of its parent, not a separate child node. Therefore it does not have any identifier, including any property for id.
// The text content of an element can be added like this:
var element = document.creteElement("div");
element.id = 1;
var elementContent = document.createTextNode("Hi I'm a text node");
elementContent.id = 2; // Will not work
element.appendChild(elementContent);
<!-- The html created from the js above -->
<div id="1">
"Hi I'm a text node" <!-- No id, just text -->
</div>
Editing a TextNode
object
There are several methods that can be used:
const newContent = "Hi! I'm a new content";
// Only change the value of text node
element.firstChild.nodeValue = newContent;
// Overwrite the whole content into newContent
element.innerText = newContent;
// Use innerHTML when HTML parsing is neccessary
var paragraph = document.querySelector('p')
paragraph.innerHTML = "I'm an <em>emphasized</em> content"
textContent
- Gets the content of all TextNodes in the sub-tree as raw text.
- The return value includes the text of hidden elements such as
<script>
and<style>
.
innerText
- Gets the content of “human-readable” element as raw text.
- Accessed as
element.innerText
- Takes styles into consideration and does not include the text of hidden elements such as
<script>
and<style>
.
nodeValue
- Gets the content of the current node. (Same as
innerText
) - Accessed as
element.childNodes[0].nodeValue
- Used for best performance!
- Gets the content of the current node. (Same as
innerHTML
- Parses the content as
HTML
. (text/html
) - Using
innerHTML
to insert text into a web page may create a potential security risk. (potential to become an attack vector on a site)
- Parses the content as
Leave a comment