HTML Javascript get textNode by id tag nothing?

Is there anyway to assign an id to a text node and then retrieve that text node via that id? I have tried several different ways and keep getting errors saying that it cannot get the null property.

My code looks something like this:

 var myDiv = document.createdElement('div');
 myDiv.id = "textContainer";

 var textNode = document.createdTextNode("some text");
 textNode.id = "descriptionText";
 myDiv.appendChild(textNode);

      

Works well up to this point; it is displayed on the page. Later I will try to change this node text and the one where I am getting errors.

 var tempNode = document.getElementById(descriptionText);
 descriptionText.value = "new text";

      

And this is not an option. I've tried options like text naming node with tagName, data, etc. and I get the same error. So, isn't it possible to name and retrieve the text node? And the next best solution for creating new text nodes and replacing the old text node?

+3


source to share


1 answer


Text has no property for id, so when you write a node to the DOM it is not available, the path is greater. What you create in JavaScript (an object Text

) does not directly correlate to a DOM element like HTMLElement .

In fact, it is not even considered a child of the parent, it is the textContent

parent. Notice what textContent

comes from the element that inherits from Node

.

You can assign an "id" to an object when you create it, because all objects are just objects, but when you place them in the DOM, all non-standard materials disappear.

If you are testing a parent for it:

myDiv.children.length;

      

You will see that (if there are no other children), the text node you added is "consumed" by the parent as a property.



Here's a little jsfiddle demonstrating.


Side note: This is an oversimplification of how text is handled in the browser. I don't know if I can call this a gross oversimplification, but this is one way.

It should be noted that Text inherits from CharacterData , which in turn inherits from Node . However, these are interfaces that limit the scope of available methods / properties.

Also, text nodes always available in the DOM, but not through IDs or tags. The MDN page forNode.normalize

clearly demonstrates how these nodes are accessible via the childNodes

read-only nodeList .

While it's helpful to keep this stuff in your back pocket, it probably isn't important to think of text in the context of nodes and normalization and CharacterData for day to day use.

+8


source







All Articles