Ralph
Ralph

Reputation: 6399

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.

Upvotes: 20

Views: 59180

Answers (6)

Dmitriy Buldakov
Dmitriy Buldakov

Reputation: 51

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

Upvotes: 4

TeKapa
TeKapa

Reputation: 546

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"

Upvotes: 2

meder omuraliev
meder omuraliev

Reputation: 186562

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

Upvotes: 28

Matthew
Matthew

Reputation: 2280

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

Upvotes: 0

Scott Saunders
Scott Saunders

Reputation: 30394

var x = the object you got
var theOldText = x.innerText
x.innerText = "new text"

Upvotes: 0

Chris Ballance
Chris Ballance

Reputation: 34347

try this

.InnerText

Upvotes: -2

Related Questions