Ralph Ralph - 1 year ago 117
Javascript Question

Getting the value of text from a text object in JavaScript

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.

Answer Source
<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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download