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>
|
|
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 |