20

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.

6 Answers 6

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

5
  • I forgot to specify lastChild, I just added it now. Oct 29, 2009 at 21:24
  • @meder Don't think your tactical downvoting of everyone else's answer has gone unnoticed. Oct 29, 2009 at 21:30
  • @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. Oct 29, 2009 at 21:44
  • @Corey - I didn't test this in IE but let me know if it doesn't work. Oct 29, 2009 at 21:50
  • @meder "my answer is better" is a flimsy excuse for Tactical Downvoting, but at least you owned up to it. Oct 29, 2009 at 22:44
4

you can access text content of the [object Text] by the "data" property. this property is R/W so that you can use it to read text as well as to write it.

<div><img id="my_img_1" src="img1.gif">My Text</div>
<script>
    alert('my current text = ' + lastChild.data);
    lastChild.data = 'new text';
</script>

you can find more here

2

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"
0
var x = the object you got
var theOldText = x.innerText
x.innerText = "new text"
0

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');
-2

try this

.InnerText

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.