如何仅使用 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

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

How can get the text of a div tag using only javascript (no jQuery)

javascripthtml

提问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 textContentinstead of innerHTML.

您可能想尝试textContent而不是innerHTML.

Given innerHTMLwill return DOM content as a Stringand not exclusively the "text" in the div. It's fine if you know that your divcontains only text but not suitable if every use case. For those cases, you'll probably have to use textContentinstead 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 textContentis not supported in IE8 and older, here is a workaround:

因为textContentIE8 及更早版本不支持,这里是一个解决方法:

var node = document.getElementById('test'),
var text  = node.textContent || node.innerText;
alert(text);

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

innerHTMLand innerTextis 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 objectdirectly by id:

您可以通过以下方式object直接使用它id

text = test.textContent || test.innerText;
alert(text);