如何才能获得一个div标签的文本只使用javascript(没有jQuery) [英] How can get the text of a div tag using only javascript (no jQuery)

查看:103
本文介绍了如何才能获得一个div标签的文本只使用javascript(没有jQuery)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述



  function test(){
var t = document。 。的getElementById( '超人')值;
alert(t); }

有没有什么办法可以使用简单的Javascript获取值没有jQuery请!

解决方案

您可能会尝试使用 textContent 而不是 innerHTML $ b 给定 innerHTML 将返回DOM内容为字符串,而不是专用于 div 中的文本。如果你知道你的 div 只包含文本,但在每个用例中都不适合,那就好了。对于这些情况,您可能必须使用 textContent 而不是 innerHTML



例如,考虑以下标记:

 < div id =test> 
一些< span class =foo>样本< / span>文本。
< / div>

您会得到以下结果:

  var node = document.getElementById('test'),

htmlContent = node.innerHTML,
// htmlContent =一些< span class =foo>样本< / span>文字。

textContent = node.textContent;
// textContent =一些示例文本。

详情请参阅MDN:


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!

解决方案

You'll probably want to try textContent instead of 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

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:

这篇关于如何才能获得一个div标签的文本只使用javascript(没有jQuery)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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