How do I select text nodes with jQuery?

前端 未结 11 1525
独厮守ぢ
独厮守ぢ 2020-11-21 04:30

I would like to get all descendant text nodes of an element, as a jQuery collection. What is the best way to do that?

11条回答
  •  你的背包
    2020-11-21 05:04

    I was getting a lot of empty text nodes with the accepted filter function. If you're only interested in selecting text nodes that contain non-whitespace, try adding a nodeValue conditional to your filter function, like a simple $.trim(this.nodevalue) !== '':

    $('element')
        .contents()
        .filter(function(){
            return this.nodeType === 3 && $.trim(this.nodeValue) !== '';
        });
    

    http://jsfiddle.net/ptp6m97v/

    Or to avoid strange situations where the content looks like whitespace, but is not (e.g. the soft hyphen ­ character, newlines \n, tabs, etc.), you can try using a Regular Expression. For example, \S will match any non-whitespace characters:

    $('element')
            .contents()
            .filter(function(){
                return this.nodeType === 3 && /\S/.test(this.nodeValue);
            });
    

提交回复
热议问题