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

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

get text of an element without children in javascript

javascriptjquerytextchildren

提问by Nik

How do I get the text of an element without the children? Neither element.textContentnor element.innerTextseem to be working.

如何在没有子元素的情况下获取元素的文本?既不工作element.textContent也不element.innerText似乎工作。

HTML:

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>

and here's the foolfunction:

这是fool功能:

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("");
    }
}

edit: using node.nodeTypedoesn't really help and here's why: Imaginge the following HTML

编辑:使用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>

if I'd use nodeType, only the text of the aelement would change , but not the tditself ("last visit....")

如果我使用nodeType,只有a元素的文本会改变,而不会改变td它本身(“最后一次访问......”)

回答by Pointy

Just find the text nodes:

只需找到文本节点:

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

edit— if you wantthe text in descendant ("children") nodes, and (as is now apparent) you're using jQuery:

编辑— 如果您想要后代(“子”)节点中的文本,并且(现在很明显)您正在使用 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;
};

Hold on and I'll test that out :-) (seems to work)

稍等,我会测试一下:-)(似乎有效)

回答by fredrikekelund

This code achieves the same result as the two other answers, but in a more expressive, functional way. The filterand maparray methods are supported in all modern browsers (IE9 and up).

此代码实现了与其他两个答案相同的结果,但以更具表现力、更实用的方式实现。在filtermap阵列方法在所有现代浏览器(IE9及以上)的支持。

Throwing this in there since the other answers are a bit dated by now.

把这个扔在那里,因为其他答案现在有点过时了。

var content = Array.prototype.filter.call(element.childNodes, function (element) {
    return element.nodeType === Node.TEXT_NODE;
}).map(function (element) {
    return element.textContent;
}).join("");

回答by Johannes Egger

The text of an element is also a separate node. Consider this piece of code:

元素的文本也是一个单独的节点。考虑这段代码:

<span>
    Some text
    <span>Inner text</span>
    More text
    <span>More inner text</span>
    Even more text
</span>

What do you mean now when you say you want the text of the element? Just the direct children?

当你说你想要元素的文本时,你现在是什么意思?只是直系孩子?

Then this piece code of code may help:

那么这段代码可能会有所帮助:

for (var element in elements) {
    if (element.nodeType == Node.TEXT_NODE) {
        // do something
    }
}

回答by user2426679

In addition to answers like Pointy, handling newline character for <br/>can be done like this:

除了像 Pointy 这样的答案之外,<br/>还可以像这样处理换行符:

txt = '';
for (var i = 0; i < element.childNodes.length; ++i)
    if (element.childNodes[i].nodeType == 3) {
        txt += element.childNodes[i].textContent;
    } else if (element.childNodes[i].nodeType == 1) {
        name = element.childNodes[i].nodeName || element.childNodes[i].tagName || '';
        if (name.toUpperCase() == 'BR') {
            txt += '\n';
        }
    }
return txt;