Let’s say I have the following HTML:
<div class="Main">
<div class="About_Sports">
<div class="sportsPhoto">
<div class="content">
<div class="location">
<div class="title">Badminton is a racquet sport played using racquets to hit a shuttlecock across a
net. Although it may be played with larger teams</div>
<div class="description">Games employing shuttlecocks have been played for centuries across
Eurasia,[a] but the modern game of badminton developed in the mid-19th century among the
expatriate officers of British India as a variant of the earlier game of battledore and
shuttlecock. ("Battledore" was an older term for "racquet".)[4] Its exact origin remains
obscure. The name derives from the Duke of Beaufort's Badminton House in Gloucestershire,[5] but
why or when remains unclear.</div>
</div>
</div>
</div>
<div class="sportsPhoto">
<div class="content ">
<div class="location">
<div class="title">Tennis is a racket sport that is played either individually against a single
opponent (singles) or between two teams of two players each (doubles).</div>
<div class="description">The four marquee tennis tournaments every year, the Grand Slams -
Australian Open, French Open, Wimbledon and the US Open - provide high-quality action throughout
the year in addition to various lower-level tournaments to keep fans engaged.</div>
</div>
</div>
</div>
</div>
</div>
I want to check and limit the text inside each description
div to 20 characters if it’s parent title
is 10 characters long. However, if the title is more than 10 characters long, than I want to completely hide the text inside the description
(for e.g display: none
)
How would I go about doing this?
I thought of doing something like this (below), but I’m not sure how do I check for each title
and description
divs, if there are multiple of them on the page.
if ($(".About_Sports.sportsPhoto.content.location").length > 0) {
if($(this).closest('.title').children('.description')){
}
}
2
Answers
To do this you need to loop over all the
.title
elements and check their lengths. From there you can act upon the sibling.description
as needed:You need to loop over
.description
div and check its.prev()
title text lengthand add your condition accrodingly.