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
asp.net-web-api
merge
c99
pagination
datastore
interface
serialization
knitr
sublimetext
google-cloud-functions
hugo
tvos
nfs
extjs4.2
32bit-64bit
google-schemas
minecraft-forge
redis-sentinel
foreign-keys
digital-signature
cfml
bourbon
sar
kendo-mobile
scriptella
roundup
motion-detection
appirater
fractions
8051
carrierwave
ntp
reactjs.net
sharding
hivemq
magento-1.9.2.4
wurfl
modernizr
flatmap
bc
css-position
linq-to-objects
hackintosh
kill
watchface
preloader
install.packages
chronicle-map
congestion-control
dynamic-linq
lampp
globalize
vugen
stdmap
oracleclient
opengl-4
builtins
preprocessor
lrs
resourcemanager
kango-framework
project-organization
cda
kendo-upload
inf
sciruby
rewrite
sony-lifelog-api
uncompress
rdflib
skspritenode
snackbar
mraid
kubuntu
mass-assignment
webmatrix-3
uncaught-typeerror
mruby
viewer
crowd
administration
universal-image-loader
mobility
ss7
ray
vbe
twitter-bootstrap-rails
ie8-compatibility-mode
cnf
route-provider
octal
server-administration
preload
midlet
boost-signals
role
expression-blend-4
saxparseexception
inline-formset
django-paypal
spread
linfu-dynamicproxy
lemmatization

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