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.
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.
<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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With