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

Sovary October 5, 2021 364
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

Founder of CamboTutorial.com, I am happy to share my knowledge related to programming that can help other people. I love write tutorial related to PHP, Laravel, Python, Java, Android Developement, all published post are make simple and easy to understand for beginner. Follow him