如何使用 JavaScript 获取段落中的文本

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/27609140/
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-10-28 07:42:02  来源:igfitidea点击:

How get the text inside a paragraph with JavaScript

javascripthtmldom

提问by Maroxtn

I am trying to get the text inside p tag

我正在尝试获取 p 标签内的文本

 <p id="paragraph">Some text</p>

And i want to store the text in JavaScript variable like this

我想像这样将文本存储在 JavaScript 变量中

 var text = "Some text";

I read that i have to add

我读到我必须添加

 var text = document.getElementById("paragraph").innerHtml;

But the value of the variable is NULL or Undefined and i did also like this

但是变量的值是 NULL 或 Undefined 我也喜欢这个

 var text = document.getElementById("paragraph")[0].innerHtml;

And i had the same problem !

我有同样的问题!

回答by Alexander T.

In your example you are using incorrect property name, must be innerHTML(note- case sensitivity HTMLnot Html) not innerHtml

在您的示例中,您使用了不正确的属性名称,必须是innerHTML注意-HTML不区分大小写Html)不是innerHtml

var text = document.getElementById("paragraph").innerHTML
                                                     ^^^^

回答by Travis J

You should probably use .textContentto get the text to make sure you don't get extra markup in your text variable.

您可能应该使用.textContent获取文本以确保您的文本变量中没有额外的标记。

var paragraph = document.getElementById("paragraph");
var text = paragraph.textContent ? paragraph.textContent : paragraph.innerText;//IE uses innerText

innerHTML returns the HTML as its name indicates. Quite often, in order to retrieve or write text within an element, people use innerHTML. textContent should be used instead. Because the text is not parsed as HTML, it's likely to have better performance. Moreover, this avoids an XSS attack vector.

innerHTML 如其名称所示返回 HTML。很多时候,为了在元素中检索或写入文本,人们使用innerHTML。应该使用 textContent 代替。因为文本不会被解析为 HTML,所以它可能具有更好的性能。此外,这避免了 XSS 攻击向量。

https://developer.mozilla.org/en-US/docs/Web/API/Node.textContent

https://developer.mozilla.org/en-US/docs/Web/API/Node.textContent

回答by Sampath Liyanage

var text = document.getElementById("paragraph").innerHTML;