...

View Full Version : Changing text with the DOM



_Q_
12-07-2005, 08:12 AM
Hi,

Whats the best way to change text using the DOM? innerHTML makes it easy - for example, I can change the text of a div by indexing the div by its id and then setting its innerHTML.

With the DOM, its easy to get to an element becuase you can use its id. But to get to the insides of an element, you have to delve into the children.

Can I be garaunteed that the first child of a div will be the textnode I want?

I feel as if I'm groping blindly in the dark after I get my div and start changing the children. I can get things to work that way, but I don't feel comfortable about it.

Is there a better way??

-Q

Kor
12-07-2005, 10:03 AM
It depends on your need.

1. innerHTML is easier if the variable to be inserted has a resonable length. And is faster. Well, it is not a DOM recomandation, but all the modern browsers has implemented it. It is a wise method (one of the IE few good "inovations" :D )

1. a related DOM method is data

document.getElementById('mydiv').firstChild.data='newtext'
...
<div id="mydiv">oldtext</div>

but you need to be sure that firstChild exists. If the HTML is written
<div></div>
it woun't work, it must be at least
<div>&nbsp;</div>

so that you may use the third DOM method

3.
var myDiv = document.getElementById('mydiv');
var newText = document.createTextNode('newtext');
myDiv.appendChild(newText);

The third method is not a replacement method, but an appending method, so that if you want to replace a text you may use either alternate replaceChild() method, or data method. Or, as I said, innerHTML

Bill Posters
12-07-2005, 10:17 AM
Fwiw, you can check the nodeType. Text nodes are type 3.
A basic example which uses the nodeType check with the replaceChild method might look like this…

(rough) e.g.

function replaceTxt() {

var obj = document.getElementById('myObj');
var newText = document.createTextNode('Blah blah blah.')

var objChildren = obj.childNodes;

if (objChildren.length>0) {
for (i=0; i<objChildren.length; i++) {
if (objChildren[i].nodeType == 3) {
var currentText = objChildren[i];
obj.replaceChild(newText, currentText);
}
}
} else {
obj.appendChild(newText);
}

}

The above method also checks to see if there is any text to start with. If there is, it uses the replaceChild method. If thre isn't, it uses the appendChild method.

_Q_
12-08-2005, 05:41 AM
Thanks guys - thats very helpful.

-Q

navkrish
02-09-2009, 02:30 PM
But this is not Reflecting in the original file. wat can we do for tat plz help on this .. (like cms)

navkrish
02-09-2009, 02:33 PM
hello sir , this is working fine but i want write in the same file means . it should reflect in tat div .. plz help me on this issue .. the main reason is i want to build an application like cms ..



EZ Archive Ads Plugin for vBulletin Copyright 2006 Computer Help Forum