Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting the value of text from a text object in JavaScript

Tags:

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.

like image 617
Ralph Avatar asked Oct 29 '09 21:10

Ralph


People also ask

How do I get text in JavaScript?

Use the textContent property to get the text of an html element, e.g. const text = box. textContent . The textContent property returns the text content of the element and its descendants. If the element is empty, an empty string is returned.


1 Answers

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

like image 95
meder omuraliev Avatar answered Oct 16 '22 14:10

meder omuraliev