1

I'm looking to loop through divs, check if each has content within it's specific child div, if so add a class to the div.

  $('.img-banner').each(function( index, element ) {
    if ( $(element).find('.img-banner-content').length > 0 ) {
      $(element).addClass("has-content");
    }
  });

I'm missing something simple here and could do with a shake. The issue is it's adding the class "has-content" to all divs.

Reduced test case: JSFiddle

Thanks all.

wbdlc
  • 1,070
  • 1
  • 12
  • 34
  • Your only test here is to check if there's one or more `divs` within the parent `div`. There's nothing checking for their content. – emerson.marini Jun 22 '16 at 18:16
  • Possible duplicate of [How do I check if an HTML element is empty using jQuery?](http://stackoverflow.com/questions/6813227/how-do-i-check-if-an-html-element-is-empty-using-jquery) – 4castle Jun 22 '16 at 18:20

1 Answers1

5

You need to actually check if there is text within the div.

$(this).find('.img-banner-content').length will always return true since it's not actually checking if that dom node has any innerHTML, just whether the dom-ref present.

So replace:

if ( $(this).find('.img-banner-content').length > 0 )

With:

if ( $(element).find('.img-banner-content').text().length > 0 )

Putting it together:

$(document).ready(function () {
  $('.img-banner').each(function( index, element ) {
    if ( $(element).find('.img-banner-content').text().length > 0 ) {
      $(element).addClass("has-content");
    }
  });
});

https://jsfiddle.net/jg0w257q/

Jonathan.Brink
  • 23,757
  • 20
  • 73
  • 115
  • Alternatively and for more flexibility, use `.html()`. A `$.trim()` operation might also be used. – 4castle Jun 22 '16 at 18:17
  • @4castle good point, but I'm not sure if the original intent is simply to check if there is text within the div, or if there is actually a bunch of dom nodes and stuff there – Jonathan.Brink Jun 22 '16 at 18:20
  • 1
    @Jonathan.Brink no, this is perfect. Just what I was looking for. Thank you for breaking in down. I was looking to check if there is text within the div. – wbdlc Jun 22 '16 at 18:23