Change the styling of a DIV depending on the character count of a text within another DIV using JQuery

My website contains a series of div elements that display an image, title, and excerpt. Some of the content divs have titles that span two lines, while others have shorter one-line titles. I would like to add a different class to the excerpt div if the title is one line and contains 24 characters or less.

To achieve this, I plan to utilize a jQuery function that iterates through each '.content' div and then uses an if statement to check the character length of the '.contentTitle'. If the condition is met, the function will apply a specific class to the '.excerpt' div within the same parent .content div.

The code snippet I've attempted so far doesn't seem to be working as expected. I suspect it may be due to both the '.contentTitle' and '.contentExcerpt .excerpt' divs being 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 №1

When working with the child elements of the container div (.content), it's important to ensure that you are also checking the children of the div itself. This is necessary because if there are multiple parent .content divs and one of them has a length >= 22, the condition will fail when only checking the contentTitle text length.

To address this issue, I have adjusted the code below to include checking 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: After updating your code as shown above, you'll notice that the color doesn't change as expected when one of the matching divs has a length >= 22.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Implementing the change method in Angular2 and JavaScript

Within my application, I have implemented two select elements. The objective is that when one select element is altered, the other will automatically change as well. Furthermore, I need to be able to detect the event when the second select element is modif ...

Exploring the concept of importing components from different pages in NextJS

I'm currently navigating the Next.JS framework and struggling to grasp the concept of importing data from a component page. Let's say I've created a page named example.js in my components folder, where I'm fetching data from an API to d ...

Assigning numerical ratings to a web-based questionnaire in HTML

In my questionnaire, I have radio buttons and checkboxes that need to be graded. The format of the input elements looks like this: <input type="radio" name="1" value="Yes" onclick="document.getElementById('pls').setAttribute('requi ...

Utilizing relative URIs in Node.js request library

I've encountered an issue with my code where node.js is unable to resolve the url: const request = require('request') const teamURL = `/users/${user._id}/teams`; const req = request({ url: teamURL, json: true }, function(error, ...

Counting up in Angular from a starting number of seconds on a timer

Is there a way to create a countup timer in Angular starting from a specific number of seconds? Also, I would like the format to be displayed as hh:mm:ss if possible. I attempted to accomplish this by utilizing the getAlarmDuration function within the tem ...

Tips for transferring data to an entry component in Angular 2 using ng-bootstrap modal

I've been grappling with sending data to a custom modal content component in Angular 2. My objective is to have the flexibility of calling this modal from any other component without duplicating code. Despite my efforts, including referencing the "Com ...

Issues within jQuery internal workings, implementing improved exception handling for fn.bind/fn.apply on draggable elements

I've been experimenting with wrapping JavaScript try/catch blocks as demonstrated on this link. It functions properly, essentially encapsulating code in a try/catch block to handle errors like so: $.handleErrors(function(e){ console.log("an erro ...

Text input in Bootstrap not reaching full width

Trying to achieve a Bootstrap textfield embedded in a panel that spans 100% of the remaining space-width within the panel. However, this is the result obtained: The blue border represents the edge of the panel. Below is the code being used: <div clas ...

Give GetElementsByClassName a shot

Hey, have you tried using js ref_doc_getelementsbyClassName? "I keep getting the error message 'Uncaught TypeError: Cannot set property 'value' of null' " Check out this HTML code snippet: <input type="text" cla ...

What are some javascript libraries that can be used to develop a mobile image gallery for both Android and iPhone

I currently have the touch gallery system in place, but unfortunately it isn't functioning properly on Android devices. ...

Applying the 'overflow: scroll' property creates a scroll bar that remains fixed and cannot be scrolled

Looking to showcase the seating arrangement in a cinema hall. If the seats occupy more than 50% of the page, I want a scroll bar to appear. Attempted using "overflow-scroll" without success. View result image <div class="w-50"> <div ...

Managing a single repository with multiple packages using npm

Currently, I am in the process of developing a node.js application that requires scalability and maintainability. The concept revolves around having a single repository with multiple modules embedded within it. We have opted to utilize local modules with ...

The ticking clock between the beginning and final moments

I am using jQuery and trying to create a countdown timer between a start time and end time. While I have successfully calculated the difference between the two times, I am unsure how to count down the time stored in the difference variable in my code: v ...

Transforming a triangular shape into a square using Plane Geometry in THREE.js

I have an animation created with triangles in the link below. Is there a way to convert these triangular areas into squares? The animation currently has a line running through the middle when using "PlaneGeometry". Removing this line would turn the triangl ...

Exploring Codeigniter's search feature with pagination

Incorporating search with pagination has been successfully implemented. The controller function is as follows: public function search() { if($_POST) { $search_name=$this->input->post('search_name'); ...

Ways to create a unique animation for reducing the width of a div in a specific direction?

Currently, I have managed to animate the decrease in width of a div element. However, it is currently decreasing from right to left, and I would like it to decrease from left to right instead. Can someone please provide guidance on how to achieve this? ...

Utilize ES6 syntax to bring in a package as an extension of another package

To expand map projections in D3, it is recommended to import the necessary packages like so: const d3 = require("d3") require("d3-geo-projection")(d3) This allows you to access methods such as d3-geo-projection's geoAiry method fr ...

saving a JSON element in a JavaScript array

Currently, I am utilizing AJAX to fetch data from a database using PHP and then converting it into JSON format. <?php echo json_encode($data); ?> This is the AJAX function being used: ajaxCall("getdata.php", container, function (data) { var co ...

Is it safe to utilize an AngularJS filter for parsing a URL?

When working on a web application, my client-side (angularjs based) receives JSON data from a web service. The JSON can contain a text field with some URLs, such as: blah blah ... http://www.example.com blah blah blah ... To render these links as HTML, I ...

Creating dynamic backend routes in NextJS is a great way to add flexibility to

Is there a way for me to implement dynamic backend routes? I am working on an image hosting platform where users should be able to save their images on the server under unique domains like http://localhost/<random_id>. An example link would look so ...