cheerio


Accessing the text of a class that contains other elements using Cheerio


I only want to access h1's text (H1 title is here in this case), but it prints everything. I tried adding .remove('.small-title') before text(), but it didn't work.
<div class="modal-know>
<h1>
H1 title is here
<div class="small-title">
Click
Click 2
</div>
</h1>
</div>
Node.js code
var newsTitle = $2('.modal-know h1').text(); // prints out everything
console.log(newsTitle);
have a look at cheerio docs: text()
it says
including their descendants
That is the same behaviour that jQuery .text()
So maybe this answer could help you :jQuery: using .text() to retrieve only text not nested in child tags
Here you have the code I tested:
let newsTitle = $('.modal-know h1').contents()[0].nodeValue;
// solution 2:
// .clone() //clone the element
// .children() //select all the children
// .remove() //remove all the children
// .end() //again go back to selected element
// .text(); // prints out everything
//solution 3:
// .contents().filter(function(){
// return this.nodeType == 3;
// })[0].nodeValue;
console.log(newsTitle);
*in your code sample ther is a missing " in the div modal-know class
<div class="modal-know> -> <div class="modal-know">

Related Links

confused about cheerio nextUntil
Get the text of the current node only
Accessing the text of a class that contains other elements using Cheerio
cheerio reading children of script tag
how to extract info in this kind of html using cheerio?
Cheerio not finding table content

Categories

HOME
django
string
angular-formly
jmx
numbers
components
camera
scripting
spring-session
little-proxy
commonjs
text-mining
emoji
x-cart
speech-synthesis
capistrano3
fileserver
git-extensions
gmm
solrcloud
react-toolbox
mongoid6
qliksense
epsilon
short-url
beta
jboss6.x
interbase
syntax-highlighting
motion-detection
entity-relationship-model
bringtofront
custom-controls
hreflang
gnat-gps
fossil
lubridate
openerp-7
salesforce-communities
flatmap
ods
plr
android-checkbox
stylecop
textsum
jquery-ui-draggable
convex-optimization
carrot2
stdmap
truezip
boo
reshape
javafx-css
materialized-path-pattern
meteor-packages
grails-plugin
aurora
java-money
iokit
computer-architecture
finalbuilder
ocra
sql-server-data-tools
apache-commons-daemon
nsurlsessiondatatask
openbabel
delayed-execution
pseudo-class
unix-socket
build-script
parallel-testing
functional-java
memset
rolify
nevron
pagedown
ilasm
gobject-introspection
denied
htdocs
xcelsius
commerceserver2007
cruisecontrol.rb
feasibility
lobo-cobra

Resources

Mobile Apps Dev
Database Users
javascript
java
csharp
php
android
MS Developer
developer works
python
ios
c
html
jquery
RDBMS discuss
Cloud Virtualization
Database Dev&Adm
javascript
java
csharp
php
python
android
jquery
ruby
ios
html
Mobile App
Mobile App
Mobile App