开发者

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 t开发者_如何转开发o get the object that contains the text by using lastChild, but can't figure out how to get the value of the text itself.


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


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


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"


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


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


try this

.InnerText
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜