John the Painter
John the Painter

Reputation: 2615

Add class if list item includes x element

Got a quick one, hopefully. I have these two list items included below. The font color for the royalHtmlContent is grey, but I need the font color to be white if it has royalImage within the royalSlide list item.

<li class="royalSlide" style="height: 420px; width: 610px; ">
<div class="royalHtmlContent">Text</div>
</li>

<li class="royalSlide" style="height: 420px; width: 610px; ">
<img class="royalImage" src="#" width="610" height="420" style="margin-left: 0px; margin-top: 0px; ">
<div class="royalHtmlContent royalHtmlContentOverlay">Text text text</div>
</li>

I tried this, but it's not working... it's just applying the class (which will have the style for white font color) to all the royalHtmlContent. I need it to do this only if it has royalImage within the list too.

if ($('.royalSlide').has('.royalImage')) {
    $('.royalHtmlContent').addClass('royalHtmlContentOverlay');
}

Thanks in advance, R

Upvotes: 0

Views: 82

Answers (2)

Rune FS
Rune FS

Reputation: 21752

Your code does not work for two reasons (prioritized)

  • A jQuery selection alwyas returns a selection and never a falsy value so the condition is always met
  • the selection used in the if is independant of the selection inside the if.

Start by selecting the image. If the selection is empty the rest of the chain will not do anything

$(".royalSlide > .royalImage").next("div.royalHtmlContent")
                              .addClass('royalHtmlContentOverlay');

Upvotes: 2

Alias
Alias

Reputation: 3091

$('img.royalImage').next('div.royalHtmlContent').addClass('royalHtmlContentOverlay');

Think that may work too? Basically just looks for all the and if theres one there, adds a class to the div, where you can style it with css.

Upvotes: 1

Related Questions