0

So I just started with Cheerio the other day. I have a situation where I have several divs to iterate over and based on its childrens' contents I have to do different things.

The basic HTML structure:

<div class="a">
     ...
     <div class="b">Hi</div>
     ...
</div>
<div class="a">
...

Here is the javascript:

$('.a').each(function(){
    if($('.b', ??).eq(0).html() == "Hi") ...
    else($('.b', ??).eq(0).html() == "Bye") ...

The question is what to put in the ??. I can't just put ".b" cause that won't give me the contents specific for that div. Optimally I would like to pass "this" or "$(this)". But neither of them are DOM elements.

I was just wondering what the most clean solution to this problem is. I could try grabbing the n-th children of the div. But what if ".b" isn't guaranteed to be the n-th child? I also thought about getting the HTML from $(this) then creating a new DOM but that seems like another inefficient hack.

Thanks

Vangogh500
  • 939
  • 1
  • 7
  • 17
  • http://stackoverflow.com/questions/30523117/select-special-selector-after-this-selector/30523129#30523129 will help you – Tushar Sep 03 '15 at 11:16
  • you can use `$(".a .b")` for selecting child divs – Flake Sep 03 '15 at 11:45
  • I've not used cheerio, but if it's essentially the same selectors, there are several ways to do this. One way using `:contains()`: http://jsfiddle.net/o3e43gem/ ([Passing `.a` as the context selector](http://jsfiddle.net/o3e43gem/1/), or [just any `.b` with that as the text](http://jsfiddle.net/o3e43gem/2/)) You could also use `.filter()` to select on the `.b` elements with a more sophisticated check. – Jared Farrish Sep 03 '15 at 11:56

1 Answers1

0

You can use

$('.a').each(function(){
    $(this).find('.b').eq(0).html(); ....
}
Mihai Dinculescu
  • 19,743
  • 8
  • 55
  • 70
Victor Radu
  • 2,262
  • 1
  • 12
  • 18