JQuery find text nodes with no selector on nested elements only work with .contents () and filter ()

Please help me understand why this is happening.

(UPDATE) TL; DR: the text of nested elements will be included when using the find selector with not (NESTED_ELEMENT), but will be excluded when using find with the filter (NESTEDT_ELEMENT) + contents + (NEXEDT_ELEMENT) + (TEXT_NODE).

I want to get text from the page, but exclude some elements. For simplicity, I only excluded the <p> element (and descendants), but when I use text() , I also get the text in the excluded element. When I filter the results with contents() to include only text nodes, only then does the selector not β€œwork” without returning text from excluded elements. See image below using code:

enter image description here Why doesn't this work without using contents() ?

Thanks.

For your comfort:

The URL I tested is this .

Code that gives me the text of the excluded element:

 $('body').find(':not(p, p *)').text() 

Code that gives me the desired text (the text of the excluded element is missing):

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

And here is the HTML part of the URL. As you can see, there is a <p> element and, as described, I want to get text from this HTML, but to exclude some elements (p was chosen for simplicity, there will be more rules in production).

 <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> 
+5
source share
1 answer

Try using .clone() , .remove() , .text()

 var filtered = $(".col-lg-12").clone(); filtered.find("p").remove(); console.log(filtered.text()) 
 <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> 
0
source

Source: https://habr.com/ru/post/1232895/


All Articles