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 replaceData()
Learn how to use the replaceData method to replace text inside a node with new text.

The "replaceData()" method is used to replace text inside the node with new text, i've used this a few times and have found it to be quite useful, and it is simple to learn. We will start out with an example first, and then I will explain it.


<div id="mydiv">jscript is fun</div>

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

var div = document.getElementById("mydiv").firstChild;
div.replaceData(0, 1, "Java");

//-->
</script>

We start off with a div element which has an id of "mydiv" so we can reference it. The div also has a text node "script is fun" which we will be altering with "replaceData()".

Now, onto the script.

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

The first line of the script is a reference to the first child inside the div element. We use the "getElementById()" method to grab the div, and then use "firstChild" to get the first child node inside the div element, which is a text node.

The next line does the text replacing, it is simple to do, and if you have used methods like "substr()", or "substring()", then you should be able to understand this with no . "replaceData()" excepts 3 parameters.

replaceData(start, end, "text")

start is a number which indicates where to start the replacing from within the string. Remember that indexing starts at 0, so the first letter in the string "jscript is fun" is "j". If you look at the example script above, and look at the start value, you will see it is 0. This is because I wanted to start the replacing at the beginning of the string.

end is a number again, this time it indicates the length of the replacement, again starting from the start value.

text this is the new text to be inserted in place of the text you are wanting replaced, so in the example above, I wanted to replace the first letter of the string with "Java".

The text in red is the part which will be replaced:

jscript is fun

and will finally end up as:

Javascript is fun

As you can see it is very simple to use, and to go along with "replaceData()" there are various other methods you can use to manipulate text nodes.

Discuss Tutorial: Using replaceData() 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.