Reputation: 12283
Below is my html code.
<div id="this">
<a href="xxx"> xx</a>
<a href="yy"> yy</a>
<a href="zzz"> zzz</a>
aaa
<a href="bbb"> bbb</a>
ccc
</div>
I have to get all children of this
div, i.e [xx,yy,zzz,aaa,bbb,ccc]
But by using the below code i can get only [xx,yy,zzz,bbb]. How to access other 2[aaa,ccc]?
const cheerio = require('cheerio');
var $ = cheerio.load('<div id="this"> <a href="xxx"> xx</a> <a href="yy"> yy</a> <a href="zzz"> zzz</a> aaa <a href="bbb"> bbb</a> ccc </div>')
$('div#this').children().each(function(i, child){
console.log($(this).text())
})
Upvotes: 0
Views: 59
Reputation: 148
Element
and Text
share the same parent Node
in the inheritance chain (DOM4 adds CharacterData
). Element.childNodes
is NodeList
and Element.children
is HTMLCollection
which is a collection of elements. jQuery.children
returns an elements collection without Text
s. You can access the raw DOM element to get what you want.
Upvotes: 1
Reputation: 3845
The issue is that [aaa,ccc]
are text nodes, which are not considered as children, what you could do is use contents
instead of children
. Bear in mind that this will returns comment nodes as well
const cheerio = require('cheerio');
var $ = cheerio.load('<div id="this"> <a href="xxx"> xx</a> <a href="yy"> yy</a> <a href="zzz"> zzz</a> aaa <a href="bbb"> bbb</a> ccc </div>')
$('div#this').contents().each(function(i, child){
console.log($(this).text())
})
Upvotes: 0