Navigation
Poll
Would you be an active poster if Ron's Guide had a message board?


Total Votes: 62
Comments: 18 — View
Past pollsPoll idea?
Rate Ron's Guide
Rate our resource at Bigwebmaster.com
Using insertData()
Using this tutorial, learn how to use the insertData() method to add text to a text node.

This is yet another method to use to manipulate text nodes.

If you read the other two tutorials on "replaceData()" and "deleteData()", then you should already have a good idea how "insertData()" works.

Right, as always, let me start with a small example.

<div id="mydiv">javascript is good for the soul</div>

<script type="text/javascript">
<!--

var div = document.getElementById("mydiv").firstChild;
div.insertData(13, " very");

//-->
</script>

To work with something, I just created a div with the id value "mydiv", and included some text inside it.

First, we need to reference the div, and to do that we use "getElementById()". Then we need to store it in a variable called "divObj". Finally then we grab the first child node of the div node, that being a text node.

var div = document.getElementById("mydiv").firstChild;

Onto "insertData()" now.

insertData(start, "new text")

The insertData() method accepts two parameters, the first parameter being an integer and the second parameter being a string of text.

start is a number where the new text is inserted, remembering that it is zero based, meaning that we start at 0, and not 1.

new text is a string of text that will be inserted.

divObj.insertData(13, " very");

In my example script, I wanted to place "very" into the text node so it would read as:

"javascript is very good for the soul"

To do that I had to count from left to right (positive number), starting at the letter "j", as that is number 0, next is "a" being 1, "v" being 2 etc ect. You get the idea?. I did this until I reached the white space between "is" and "good", which was character 13 in the index, remembering that it will be the left side of the character you counted up to, that is why I added a space in the new text.

divObj.insertData(13, " very");

That is basically it, nothing else to explain really, it is simple to use, so maybe have a read of the other tutorials covering text node manipulation.

Discuss Tutorial: Using insertData() 0 Comments
There are currently no comments on this discussion.
Post a comment
Sorry, you must be a registered member to post comments.

If you would like to register, you can do so here.
If you already have an account, please login.