JQuery, Cheerio- The way to get text without other elements wrap or outside tag

Sovary October 5, 2021 541
38 seconds read

Scraping or to navigate elements in html, we can use Jquery framwork or Cheerio to select html element via selector but sometimes we face the problem below, when we want to get the only text Hello which is outside the tag (no tag wrap).


<ul>
<li>A</li>
<li>B</li>
<li>C</li>
Hello
</ul>

Solution

To do this we gonna filter out with node type and then we gonna loop each of those node back.
 


var $outer = $("ul").contents().filter((index,element) => element.nodeType === 3 && element.data !="\n");
$outer.each((index,element) { console.log($(element).text());} ); 

 

Finally, we gonna get Hello text

JQuery  Cheerio 
Author

As the founder and passionate educator behind this platform, I’m dedicated to sharing practical knowledge in programming to help you grow. Whether you’re a beginner exploring Machine Learning, PHP, Laravel, Python, Java, or Android Development, you’ll find tutorials here that are simple, accessible, and easy to understand. My mission is to make learning enjoyable and effective for everyone. Dive in, start learning, and don’t forget to follow along for more tips and insights!. Follow him