tags:

views:

100

answers:

5

I have an HTML file which contains the following line:

<div><img src="img1.gif"><br>My Text</div>

I'm trying to select the phrase "My Text" using JavaScript so I can change it. I'm able to get the object that contains the text by using lastChild, but can't figure out how to get the value of the text itself.

+1  A: 

if you have

<div><img src="img1.gif"><br><span>My Text</span></div>

then you can do

lastChild.innerHTML gets the value and you can also do

lastChild.innerHTML="new text"
TeKapa
A: 

try this

.InnerText
Chris Ballance
A: 
var x = the object you got
var theOldText = x.innerText
x.innerText = "new text"
Scott Saunders
A: 

My suggestion would be to put the value that you want to change in it's own element that you can identify. Then you can use a simple line of jQuery:

<div><img src="img1.gif"><br><div id='myText'>My Text</div></div>

$('#myText').text('new text');
Matthew
+3  A: 
<div id="test"><img src="img1.gif"><br>My Text</div>

function getText( obj ) {
    return obj.textContent ? obj.textContent : obj.innerText;
}

function setText( obj, to ) {
    obj.textContent? obj.textContent = to : obj.innerText = to;
}

getText( document.getElementById('test') ) // 'My Text'
setText( document.getElementById('test').lastChild, 'bar' )

Note: innerText is for IE DOM, textContent is for the rest of the compliant DOM APIs such as Mozillas.

meder
cool man thanks
Ralph
I forgot to specify `lastChild`, I just added it now.
meder
@meder Don't think your tactical downvoting of everyone else's answer has gone unnoticed.
Chris Ballance
@Chris Ballance - Your answer is MS specific and will not work in modern browsers. Same with Scott's. The question did not include a jQuery tag nor can you set an ID on a text node, which is why I downvoted those.
meder
@Corey - I didn't test this in IE but let me know if it doesn't work.
meder
@meder "my answer is better" is a flimsy excuse for Tactical Downvoting, but at least you owned up to it.
Chris Ballance