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
service-worker
oracle12c
design-patterns
paraview
pagination
nunit
google-spreadsheet
yahoo-finance
sitecore
rendering
ms-access-2016
rom
spring-session
title
fhir
cmdb
gource
scsi
production
sigma.js
rubymotion
ksh
imagemap
systemtime
pimcore
interpreter
mount
fat
fable-f#
outliers
livelink
anki
complex-numbers
clickjacking
getpixel
modalviewcontroller
pdw-file-browser
searchkit
jvmti
opensmpp
doc
stringtokenizer
watchface
android-softkeyboard
escpos
android-ibeacon
globalize
mongotemplate
arq
excel-dna
avx
bbpress
cpu-cache
cmp
pure-css
stax
parfor
installshield-2010
cfchart
query-by-example
aurora
realsense
httpruntime.cache
relativelayout
computer-architecture
pypiserver
video-player
sapscript
sql-server-data-tools
botan
adehabitathr
android-vibration
gii
mintty
twitter-bootstrap-rails
getopt
rfc5322
scriptaculous
kogrid
time.h
facebook-timeline
redis-py
landscape-portrait
w3c-geolocation
cuteeditor
dot-emacs
interprocess
zen
silverlight-oob
sqlobject
product-management
httpcookie

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