HeyCameron HeyCameron - 18 days ago 10
CSS Question

If the length of a title is less than a certain amount of characters, modify a different div

I have a series of div's that are populated with an image, title & excerpt.
Many of the 'content' div's have a div with a two lined title, but I'd like for the 'excerpt' div to have a different class added if the title is one lined (24 characters or less).

I figured I'd have a jQuery function that runs through each '.content' div then an if statement compares the amount of characters in the '.contentTitle', if true then it would apply a class to the '.excerpt' div within the same parent .content div.

What I have below is not working. I'm wondering if its because both of the divs (.contentTitle / .contentExcerpt .excerpt) I'm using are children of the container div (.content)



$(".content").each(function(){
if($(".contentTitle").text().length < 22) {
$(".contentExcerpt .excerpt").addClass('TEST');
}
});

<div class="content">
<div class="contentImage"></div>
<div class="contentTitle"><?php the_title(); ?></div>
<div class="contentExcerpt">
<div class="excerpt">
<?php echo(get_the_excerpt()); ?>
</div>
</div>
</div>




Answer

When you are using the children of the container div (.content), you didn't check the children of the div whereas you check all other div matching $(".contentTitle").text().length < 22 when there is more than one .content parent div and when one of them is having the length >= 22, the condition will fail.

I have modified the code below to check the children of the parent div.

$(".content").each(function(){
  var parent = $(this);
  if(parent.find(".contentTitle").text().length < 22) {
    parent.find(".contentExcerpt .excerpt").addClass('TEST');
  }
});
.TEST {
  color: green;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="content">
  <div class="contentImage"></div>
  <div class="contentTitle">12345678901234567890123</div>
  <div class="contentExcerpt">
    <div class="excerpt">
      Test content
    </div>
  </div>
</div>

<div class="content">
  <div class="contentImage"></div>
  <div class="contentTitle">12345678901234567890</div>
  <div class="contentExcerpt">
    <div class="excerpt">
      Test content
    </div>
  </div>
</div>

Note: If you replace your code above, you can see, this is not changing the color as one of matching div is having the length >= 22.