Looping over text with conditionals

Think I got it!

function dive(root) {
  $(root).contents().each(function(node) {
    if(this.nodeType == 3 && this.wholeText.trim() !== '') {
     console.log(this.wholeText+" belongs to "+this.parentNode.tagName+" with class "+this.parentNode.classList);
    } else {
      dive(this);
    }
  });
}
dive($('figcaption'));

Results in console:

KNOW belongs to SPAN with class purple
AND belongs to SPAN with class red
BE belongs to SPAN with class orange
KNOWN belongs to P with class 
NOT KNOWN belongs to SPAN with class blue
AND belongs to SPAN with class grey
BE belongs to SPAN with class black
UNKNOWN belongs to SPAN with class green
1 Like