如何仅使用 javascript(无 jQuery)获取 div 标签的文本
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/10370204/
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
How can get the text of a div tag using only javascript (no jQuery)
提问by agurchand
I tried this but showing "undefined".
我试过这个,但显示“未定义”。
function test() {
var t = document.getElementById('superman').value;
alert(t); }
Is there any way to get the value using simple Javascript no jQuery Please!
有没有办法使用简单的 Javascript 没有 jQuery 来获取值,请!
回答by dhar
You'll probably want to try textContent
instead of innerHTML
.
您可能想尝试textContent
而不是innerHTML
.
Given innerHTML
will return DOM content as a String
and not exclusively the "text" in the div
. It's fine if you know that your div
contains only text but not suitable if every use case. For those cases, you'll probably have to use textContent
instead of innerHTML
鉴于innerHTML
将返回DOM内容为String
,并在不完全的“文本” div
。如果您知道您div
只包含文本但不适合每个用例,那很好。对于这些情况,您可能必须使用textContent
而不是innerHTML
For example, considering the following markup:
例如,考虑以下标记:
<div id="test">
Some <span class="foo">sample</span> text.
</div>
You'll get the following result:
你会得到以下结果:
var node = document.getElementById('test'),
htmlContent = node.innerHTML,
// htmlContent = "Some <span class="foo">sample</span> text."
textContent = node.textContent;
// textContent = "Some sample text."
See MDN for more details:
更多细节请参见 MDN:
回答by oabarca
Because textContent
is not supported in IE8 and older, here is a workaround:
因为textContent
IE8 及更早版本不支持,这里是一个解决方法:
var node = document.getElementById('test'),
var text = node.textContent || node.innerText;
alert(text);
innerText
does work in IE.
innerText
确实在 IE 中工作。
回答by Abdus
You can use innerHTML
(then parse text from HTML) or use innerText
.
您可以使用innerHTML
(然后从 HTML 解析文本)或使用innerText
.
let textContentWithHTMLTags = document.querySelector('div').innerHTML;
let textContent = document.querySelector('div').innerText;
console.log(textContentWithHTMLTags, textContent);
innerHTML
and innerText
is supported by all browser(except FireFox < 44) including IE6.
innerHTML
并被innerText
包括IE6在内的所有浏览器(FireFox < 44 除外)支持。
回答by Nick Wynther
Actually you dont need to call document.getElementById()
function to get access to your div
.
实际上你不需要调用document.getElementById()
函数来访问你的div
.
You can use this object
directly by id
:
您可以通过以下方式object
直接使用它id
:
text = test.textContent || test.innerText;
alert(text);