One thing we’ve not explored yet is how to add text inside of an element. Obviously, there is no HTML tag for plain text, so we can’t use the createElement function to do so. Instead, we have to use the createTextNode function. Let’s say that we want to add some text to our div and insert it after all of our images. The code we would use to do so would look something like:
mydiv.appendChild(document.createTextNode("This is some text that I'm adding to my div"));
We would now have the text “This is some text that I’m adding to my div” at the end of the div, following all of our images. Our outline would now look like:
- textnode (“This is some text that I’m adding to my div”)
I am going to take a slight detour to explore a function that does not really exist within the DOM. That function is the insertAfter function. As I said, there is no insertAfter function, so you need to do a little bit of a workaround in order to successfully insert an element after another element. Basically, in order to do that, you need to use the insertBefore function to insert your new element before the next element in the DOM.
For the purposes of an example, let’s say that we want to insert a new div after the div we’ve referenced as “mydiv”. To do so, we would use code similar to the following:
var newel = document.createElement("div"); newel.id = "newel"; newel.appendChild(document.createTextNode("This is a new div. It will be inserted after 'mydiv'")); mydiv.parentNode.insertBefore(newel,mydiv.nextSibling);
The code above will create a new div with the id of “newel”, add some text inside of it and insert it directly after our old div.
We will now build a real-world example to show you how you might be able to use these functions. In the following example, we will use the insertBefore, appendChild, createElement and createTextNode functions to manipulate the DOM.
The example above starts with a simple unordered list that contains four list items. Then, if you click on any of the top three, the text inside the li will be replaced with a text input. You can change the text any way you want to. When you jump back out of the text input, it will be converted back into a regular textnode. If you click on the last bullet item, it will insert a new text input, so that you can add additional bullet items to the list. That new bullet item will behave the same way as the items above.
You could easily manipulate the script above to allow you to remove bullets from the list, too, if you wanted to. In addition, I’m sure you can imagine how useful something like this would be when used as part of an AJAX application. You could allow users to generate their own content for their pages, and then use an AJAX function to save that new content into a database.
I hope this series of tutorials has been helpful, and that you will find new and innovative ways to utilize these functions in your own pages.