Fred J. Fred J. - 4 months ago 20
Javascript Question

extract DOM element with cherrio

This Meteor server code fails to extract the text "789" using the cherrio object $ as the docs suggests.

$('td[headers=x]').each(function() {
console.log($(this).next().html().trim()); //=> 456
console.log($(this).next('td[headers="y"]').html().trim()); //<-- fail
});


<td headers="x" class="bodyTextSmall">
123
</td>
<td headers="xx" class="bodyTextSmall">
456
</td>
<td headers="y" class="bodyTextSmall">
789
</td>


Any idea why? Thanks

Answer

.next() will only return the immediate next sibling - if a selector is used then it must match. Your headers="yy" is not the immediate next sibling but the second next. Use .siblings() with the selector instead:

$(this).siblings('td[headers="y"]').html().trim()