Javascript jQuery筛选器,返回不同的jQuery对象(即$(this).parent())

Javascript jQuery筛选器,返回不同的jQuery对象(即$(this).parent()),javascript,jquery,dom,filter,Javascript,Jquery,Dom,Filter,我试图返回包含文本(而非空白)的所有子元素(例如“body”-即DOM的一大块/全部)的对象。以下几点效果很好: function findAllSubnodesWithText( el ) { // find all subnodes that don't have subnodes themselves return $(el).find("*:not(:has(*))").filter(function ( ) { return $(this).text().trim().

我试图返回包含文本(而非空白)的所有子元素(例如“body”-即DOM的一大块/全部)的对象。以下几点效果很好:

function findAllSubnodesWithText( el ) {
  // find all subnodes that don't have subnodes themselves
  return $(el).find("*:not(:has(*))").filter(function ( ) {
    return $(this).text().trim().replace('\n', '').length > 0;
  });
}
除此之外,它会在下面的节点上跳起来(div.headline有三个子节点:text、br、text)。这意味着div中的任何内容都不会进入我的findAllSubnodesWithText()结果

但很明显,过滤器只是测试父对象是否存在,将BR添加到结果对象中。此外,如果有多个

,最好避免在结果中出现两次相同的父项

最后我想说的是:

var result = findAllSubnodesWithText('#base_node')
$(result[0]).text() = "some text in a p tag"
$(result[1]).text() = 
 "Here is some headline text split by a
line break"

你的意思是这样的吗

function findAllSubnodesWithText(el) {
    // find all subnodes that don't have subnodes themselves
    return $(el).contents().filter(function () {
        return !$(this).children().length && $(this).text()
    });
}
更新 我很困惑您到底在寻找什么(没有子节点的子节点似乎与您的示例中给出的内容相矛盾),无论如何:


一种可能的解决方案是查找所有非空文本节点并返回其父节点:

function findAllSubnodesWithText(el) {
    return $(el)
        .find("*")  // using .find instead of a recursive function
        .contents() // filter out text nodes that are not-empty (this and below)
        .filter(function () {
            return this.nodeType === this.TEXT_NODE && $.trim(this.data).length > 0
        })
        .parent();  // get parent
}

var $a = findAllSubnodesWithText(document.body);
console.log($a);

// returns
// [p, div.headline]

您能否提供另一个示例,说明应该选择什么和不应该选择什么?谢谢您的回答!对于.contents(),我有一个有趣的想法,我没有意识到它会返回这样的数组。不幸的是,它看起来只有一层深。看看我想要的输出的更新问题谢谢你关于.map()的想法,我以前没有用过。太好了!最后的.parent()是我没有得到的逻辑部分。实际上我还是不明白为什么它会起作用。过滤后,jQuery是否为过滤器的每个结果映射.parent()?我不知道你可以有一个jQuery对象列表,然后在所有对象上运行.parent()。。。jQuery是一只聪明的野兽。
function findAllSubnodesWithText(el) {
    // find all subnodes that don't have subnodes themselves
    return $(el).contents().filter(function () {
        return !$(this).children().length && $(this).text()
    });
}
function findAllSubnodesWithText(el) {
    return $(el).contents().filter(function () {
        return  $.trim($(this).text())
    }).map(function(){
        return $.trim($(this).text())
    });
}
function findAllSubnodesWithText(el) {
    return $(el)
        .find("*")  // using .find instead of a recursive function
        .contents() // filter out text nodes that are not-empty (this and below)
        .filter(function () {
            return this.nodeType === this.TEXT_NODE && $.trim(this.data).length > 0
        })
        .parent();  // get parent
}

var $a = findAllSubnodesWithText(document.body);
console.log($a);

// returns
// [p, div.headline]