The "createTextNode()" method is pretty simple to use for creating new text nodes in an HTML document using JavaScript.
A text node is basically just a place to insert new text to a document. Have a look at the example below to see how it can be used.
<script type="text/javascript">
|
|
As you can see we have a script with a variable called "myText" which is holding the text node we have just created. Creating text nodes with "createTextNode()" will just be plain text, putting in tags to make it bold, italic etc, will not work, you will need to do more work with the text node to give it style.
So, you have created your text node, but what do you do with it now? Well, now that you have created your text node, you need to append it to the document. Take a look at the script below.
<div id="mydiv"><div>
|
|
Now, just above the script is a small bit of html, a div element, this will be used to place our new text node inside of it. The Reason for the id="mydiv" is so that we can reference the object using the "getElementById()" method. We then need to use "appendChild()" so that we can insert the new text node into our div element. "appendChild()" works by inserting the new node at the end, all you need to do is add a parameter, so in this case the parameter is "myText" since that is the variable holding our new node we wish to add to the document.
Once you get a good understanding of creating new text nodes and appending them to the document, you can then look into give the text some style. An example of what I mean is below.
<div id="mydiv"><div>
|
|
Basically the same as before, but this time we are adding the new text node to a font node we have created.
var font = document.createElement("font");
|
|
The variable "font" now holds a new node we have just created, that new node being a font element.
font.style.color = "red";
|
|
I wanted to make the new text red, so I set the font style color to red.
font.appendChild(myText);
|
|
All that is left is to add the text node to the font node, so the text node will be a child of the font node, we do this by using "appendChild()" again, so if we were able to view the source we would have something basically like what you see below.
<font style="color: red;">hello world</font>
|
|
That now needs to be added to the document, so just like we did before, we appended the text node to the div, we will do the same but this time we will be appending the font node which already contains our new text node.
document.getElementById("mydiv").appendChild(font);
|
|
And finally, the last line to append the font node to the div container, which should now show some text that is red.
| Discuss Tutorial: Using createTextNode() | 0 Comments |