JQuery在嵌套元素上查找不带选择器的文本节点只能使用.contents()和filter()

mrg*_*oos 5 javascript jquery jquery-selectors

请帮助我理解为什么会这样.

(UPDATE)TL; DR:当使用find with not(NESTED_ELEMENT)选择器时将包含嵌套元素的文本,但是当使用find with not(NESTEDT_ELEMENT)+ contents + filter(TEXT_NODE)时将被排除.

我想从页面获取文本但是要排除某些元素.为简单起见,我只排除了<p>元素(和后代),但是当我使用它时text(),我也在被排除元素中获取文本.当我使用contents()仅包含文本节点来过滤结果时,只有通过不从排除元素返回文本,not选择器才"工作".请使用以下代码查看下图:

在此输入图像描述 为什么不使用它contents()

谢谢.

为了您的方便:

我测试的URL就是这个.

给我排除元素文本的代码:

$('body').find(':not(p, p *)').text()
Run Code Online (Sandbox Code Playgroud)

给我所需文本的代码(排除元素的文本不存在):

$('body').find(':not(p, p *)').contents().filter(function(){return this.nodeType == 3}).text()
Run Code Online (Sandbox Code Playgroud)

这是URL中的HTML部分.正如你所看到的那样,那里有一个<p>元素.如上所述,我想从这个HTML中获取文本但是要排除一些元素(为简单起见选择了p,生产中会有更多的规则).

<div class="col-lg-12">
                    <header id="header" role="banner" class="jumbotron">
                        <h1>
                            <img src="/img/icon/apple-touch-icon-114-precomposed.png" class="offscreen" alt="">
                            <i class="icon-html5" aria-hidden="true"></i><span class="offscreen">HTML 5</span>
                            <span>Semantics and Accessibility: <span class="subheader">Heading Structure</span></span>
                        </h1>
                        <p class="lead" id="lead_content">The more you understand the specification, the more you'll realize there are more right 
                        ways to implement <em>proper</em> semantic HTML markup than wrong. Thinking in terms of web accessibility can provide direction.</p>
                    </header>
                </div>
Run Code Online (Sandbox Code Playgroud)

gue*_*314 0

尝试使用.clone(), .remove(),.text()

var filtered = $(".col-lg-12").clone();
filtered.find("p").remove();

console.log(filtered.text())
Run Code Online (Sandbox Code Playgroud)
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js">
</script>
<div class="col-lg-12">
  <header id="header" role="banner" class="jumbotron">
    <h1>
                            <img src="/img/icon/apple-touch-icon-114-precomposed.png" class="offscreen" alt="">
                            <i class="icon-html5" aria-hidden="true"></i><span class="offscreen">HTML 5</span>
                            <span>Semantics and Accessibility: <span class="subheader">Heading Structure</span></span>
                        </h1>
    <p class="lead" id="lead_content">The more you understand the specification, the more you'll realize there are more right ways to implement <em>proper</em> semantic HTML markup than wrong. Thinking in terms of web accessibility can provide direction.</p>
  </header>
</div>
Run Code Online (Sandbox Code Playgroud)