从JavaScript中获取文本对象的文本值 [英] Getting the value of text from a text object in JavaScript

查看:177
本文介绍了从JavaScript中获取文本对象的文本值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个HTML文件,其中包含以下行:

I have an HTML file which contains the following line:

<div><img src="img1.gif"><br>My Text</div>

我正在尝试使用JavaScript选择短语My Text,以便我可以更改它。我可以使用lastChild获取包含文本的对象,但无法弄清楚如何获取文本本身的值。

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.

推荐答案

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

注意:innerText用于IE DOM,textContent用于其他兼容的DOM API,例如Mozillas。

Note: innerText is for IE DOM, textContent is for the rest of the compliant DOM APIs such as Mozillas.

这篇关于从JavaScript中获取文本对象的文本值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆