Javascript 获取节点的内部文本

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/11745355/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-24 06:57:03  来源:igfitidea点击:

getting the inner text of a node

javascript

提问by Mr. 1.0

I am having trouble getting the inner text of a particular node. I have added the example node I am working with and the javascript I have come up with. The javascript works as far as returning this <span id="goal_left">3 goals lect</span>if i log it to the console. If i add innerTextto the javascript examples it will return nothing to the console. Any ideas how to get this text?

我无法获取特定节点的内部文本。我已经添加了我正在使用的示例节点和我想出的 javascript。<span id="goal_left">3 goals lect</span>如果我将它记录到控制台,javascript 就可以返回它。如果我添加innerText到 javascript 示例中,它将不会向控制台返回任何内容。任何想法如何获取此文本?

html

html

<span id="goal_left">3 goals lect</span>

javascript: these examples return <span id="goal_left">3 goals lect</span>

javascript:这些示例返回 <span id="goal_left">3 goals lect</span>

document.getElementById("goal_left");

document.querySelectorAll("span#goal_left")[0];

javascript: these examples return nothing

javascript:这些示例不返回任何内容

document.getElementById("goal_left").innerText;

document.querySelectorAll("span#goal_left")[0].innerText;

回答by David says reinstate Monica

Probably the easiest way:

可能是最简单的方法:

document.querySelectorAll("span#goal_left")[0].firstChild.nodeValue;

Though if you always want the first node returned by querySelectorAll()you could simply use:

虽然如果你总是想要返回的第一个节点,querySelectorAll()你可以简单地使用:

document.querySelector("span#goal_left").firstChild.nodeValue;

Incidentally, I'd imagine any browser that implements querySelectorAll()probably implements textContent, giving:

顺便说一句,我想任何实现querySelectorAll()可能的浏览器都实现了textContent,给出:

document.querySelector("span#goal_left").textContent;

Just to offer a cross-browser option:

只是为了提供跨浏览器选项:

var textProperty = 'textContent' in document ? 'textContent' : 'innerText';
document.getElementById('goal_left')[textProperty]

回答by Nicolas Stamm

The innerHTMLproperty might be what you're looking for. It holds the HTML code inside an element as string.

innerHTML物业可能是您正在寻找的。它将元素内的 HTML 代码保存为字符串。

回答by Drawyan

document.getElementById("goal_left").innerHTML instead of innerText.

document.getElementById("goal_left").innerHTML 而不是innerText。

Also you might want to use jQuery for manipulating DOM elements, it's much easier and less error prone.

此外,您可能希望使用 jQuery 来操作 DOM 元素,它更容易且不易出错。