Fred J. Fred J. - 1 year ago 74
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 -->
<td class="label" valign="top" align="right" style="white-space:nowrap">
<td class="displayValue" valign="top">

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

// this produced both the texts 'drinking' and 'milk'


Answer Source

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;

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download