Fred J. Fred J. - 5 months ago 14
jQuery Question

Getting text from first sibling of given element

This jQuery like selector "cheerio" tries to get the text "milk" from the html. but fails. '$' is the cheerio object.

How can it be done? Thanks

<!-- food -->
<tr>
<td class="label" valign="top" align="right" style="white-space:nowrap">
drinking:&nbsp;&nbsp;
</td>
<td class="displayValue" valign="top">
milk
</td>
</tr>




$('*').contents().filter(function () {
if (this.nodeType == 8) { //found the comments node / title

// this produced both the texts 'drinking' and 'milk'
console.log($(this).next().text());

}
});

Answer

This code may be helpful for you.:

$('*').contents().filter(function () {
  if (this.nodeType == 8) {           //found the comments node / title
    console.log($(this.nextSibling).text());  //did work
  }
});

For some reason, not obvious to me, $(this).next(); don't work properly. So, I used the native JS nextSibling;