jquery - 获取没有子文本的元素的文本

Far*_*jil 24 javascript jquery

例如,我们有这个文件

<div id="mydiv">
    some text here 
    <div id="inner div">
         text for inner div
    </div>
</div>
Run Code Online (Sandbox Code Playgroud)

我需要#mydiv使用这样的代码获取文本:

alert($('#mydiv').text());  // will alert "some text here"
Run Code Online (Sandbox Code Playgroud)

Tat*_*nit 45

嘿试试这个":http://jsfiddle.net/MtVxx/2/

这里的特定案例的良好链接:http://viralpatel.net/blogs/jquery-get-text-element-without-child-element/(这将只获取元素的文本)

希望这可以帮助, :)

jQuery.fn.justtext = function() {

    return $(this).clone()
            .children()
            .remove()
            .end()
            .text();

};

alert($('#mydiv').justtext());?
Run Code Online (Sandbox Code Playgroud)

  • 使用.end()的+1.永远不知道存在,现在它是hella-usefull. (7认同)

Ja͢*_*͢ck 24

目前接受的答案在性能方面非常糟糕,所以我觉得有必要写一个更轻量级的答案:

$.fn.mytext = function() {
    var str = '';

    this.contents().each(function() {
        if (this.nodeType == 3) {
            str += this.textContent || this.innerText || '';
        }
    });

    return str;
};

console.log($('#mydiv').mytext());?
Run Code Online (Sandbox Code Playgroud)


Iv *_* Ov 5

就像杰克的回答一样,但不需要显式迭代(通过 .each())并收集textContents:

$('#mydiv').contents().filter(function(){return this.nodeType === 3}).text()
Run Code Online (Sandbox Code Playgroud)

或者,如果您可以使用箭头函数:

$('#mydiv').contents().filter((i, el) => el.nodeType === 3).text()
Run Code Online (Sandbox Code Playgroud)