微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

在javascript中获取没有子元素的元素的文本

如何在没有孩子的情况下获取元素的文本?
element.textContent和element.innerText似乎都不起作用.

HTML

<body>
<h1>Test heading</h1>
<div>
Awesome video and music. Thumbs way up. love it. Happy weekend to you and your family. love, Sasha
</div>
</body>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.6.4/jquery.min.js"></script>
<script type="text/javascript">
    fool("body");
</script>

这是傻瓜功能

jQuery.fn.justtext = function(text) {
    return $(this).clone()
    .children()
    .remove()
    .end()
    .text();
};

function fool(el) { 

    reverse(el);

    function reverse(el) {
        $(el).children().each(function() {
            if($(this).children().length > 0) {
                reverse(this);
                if($(this).justtext() != "")
                    reverseText(this);
            } else {
               reverseText(this)
            }
        });
    }

    function reverseText(el){
        var text = el.textContent;
        var frag = text.toString().split(/ /);
        var foo = "";
        var punctation_marks = [".",",","?","!"," ",":",";"];
        for(i in frag){
            if(punctation_marks.indexOf(frag[i]) == -1)
                foo += actualReverse(frag[i],punctation_marks) + " ";
        }
        el.textContent = foo;
    }

    function actualReverse(text,punctation_marks) {
        return (punctation_marks.indexOf(text.split("")[text.split("").length-1]) != -1)?text.split("").slice(0,text.split("").length-1).reverse().join("") + text.split("")[text.split("").length-1] : text.split("").reverse().join("");
    }
}

编辑:使用node.nodeType并没有真正的帮助,这就是原因:
想象一下下面的HTML

<td class="gensmall">
    Last visit was: Sat Mar 31, 2012 10:50 am
    <br>
    <a href="./search.PHP?search_id=unanswered">View unanswered posts</a> | <a href="./search.PHP?search_id=active_topics">View active topics</a>
</td>

如果我使用nodeType,只有a元素的文本会改变,而不是td本身(“last visit ….”)

解决方法:

只需找到文本节点:

var element = document.getElementById('whatever'), text = '';
for (var i = 0; i < element.childNodes.length; ++i)
  if (element.childNodes[i].nodeType === 3)
    text += element.childNodes[i].textContent;

编辑 – 如果你想要后代(“子”)节点中的文本,并且(现在很明显)你正在使用jQuery:

$.fn.allText = function() {
  var text = '';
  this.each(function() {
    $(this).contents().each(function() {
      if (this.nodeType == Node.TEXT_NODE)
        text += this.textContent;
      else if (this.nodeType == Node.ELEMENT_NODE)
        text += $(this).allText();
    });
  });
  return text;
};

坚持下去,我将测试出来:-)(似乎工作)

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐