Using jQuery to change the `class` of the parent `div` based on the length of a `p`

I am attempting to adjust the height of a parent div based on the length of text in its child p.descr. This is achieved by adding a specific class that corresponds to different height values in CSS. Below is the jQuery code snippet:

$(document).ready(function(){  
  $('p.descr').each(function(){
        if($(this).text().length < 90){
          $(this).parent().addClass('bigP90');
        } if($(this).text().length [90,180]) {
          $(this).parent().addClass('bigP180');
        } if($(this).text().length [181,270]) {
          $(this).parent().addClass('bigP270');
        } if($(this).text().length [271,360]) {
          $(this).parent().addClass('bigP360');
        } if($(this).text().length > 360) {
          $(this).parent().addClass('bigP450');
        }
  });
});

The issue I'm facing is that the classes bigP90 and bigP450 are getting applied correctly, but not those in between. It seems like there might be a syntax error, but I haven't been able to identify it yet. Any help would be appreciated. Thank you.

Answer №1

length [90,180] doesn't mean checking if the length is between 90 and 180. The square brackets are used for accessing array elements or object properties, so in this case it's treating length as an array and attempting to retrieve the 180th element.

In Javascript, there isn't a concise way to test for a range. The approach would be to check if a value is greater than or equal to the lower limit and less than the upper limit, like this:

if (val >= 90 && val < 180)

If you've already checked the lower limit with a previous if statement, you can utilize an else if clause to evaluate the next upper limit without redundancy.

$(document).ready(function() {
  $('p.descr').each(function() {
    var len = $(this).text().length;
    var parent = $(this).parent();
    if (len < 90) {
      parent.addClass('bigP90');
    }
    else if (len < 180) {
      parent.addClass('bigP180');
    }
    else if (len < 270) {
      parent.addClass('bigP270');
    }
    else if (len < 360) {
      parent.addClass('bigP360');
    }
    else {
      parent.addClass('bigP450');
    }
  });
});

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

Retrieving Text following an HTML Element with a Parsing Tool

I'm currently utilizing PHP Simple HTML DOM for the development of a web scraper application. Here is the HTML structure from which we need to extract the City/State name, such as "Daviston, AL" in the example below. Can anyone assist me wi ...

Dynamic Font Formatting in Rails Table Based on Conditions

I need to customize the font color of dynamic values based on the state_id. If incident.state_id = 1, the font should be red; if incident.state_id = 2, it should be yellow; and if incident.state_id = 3, it should be green. incident.state_id = 1 : state.na ...

When using Vue with CSS3, placing an absolute positioned element within a relative wrapper can cause issues with maintaining the

Just starting out with Vue and diving into the world of CSS3! I'm currently working on a component that you can check out here: https://codesandbox.io/s/yjp674ppxj In essence, I have a ul element with relative positioning, followed by a series of di ...

My attempts to load the .mtl and .obj files using THREE.js have been unsuccessful

I've been working on creating a 3D model viewer using three.js, but I'm encountering issues with loading .mtl and .obj files. Despite following a tutorial at , the only model that loads successfully is the female one. Here is the code snippet I ...

Ideas for displaying data or a message only once when selecting multiple checkboxes in jquery

code: <script> $(document).ready(function(){ $(".choose").click(function(){ job_type = $(':checked').map(function() { return this.value; }).get().join(',&ap ...

After several interactions, the CSS files fail to load

I'm currently utilizing jQuery Mobile with 3 pages, and I've noticed that after navigating between the pages, the CSS is not being rendered properly. LoadCss.js $(document).on("pageinit",function(event) { $("#categoriesPage").on('pages ...

Autocomplete causing issues with Mui visual display

Encountering an issue with my Mui components login page where autofill information collapses the placeholder. Essentially, when a saved username and password autofills the fields, the autocomplete details overlap with the placeholder text. See Bug Screens ...

I currently have two responsive menus and I'm trying to figure out how to modify the javascript so that when one menu is opened, the other

I am facing an issue with my responsive menus on a webpage, similar to the example provided in the jsfiddle link below. Currently, when one menu is open and I click on another, both remain open. How can I modify the JavaScript code so that when one menu op ...

Inaccuracies arise when trying to interpret a JSON string as an object

I have tried various solutions found on stack overflow, but none of them seem to work for me. I am attempting to call an asmx web service using jQuery. Below is my code: <script type="text/javascript"> $(document).ready(function () { ...

Discover the ultimate guide to implement a captivating visual overlay using CSS

I've crafted some links using CSS to incorporate a background image (to give it the appearance of a button) employing the subsequent code: <a class="btnImg" id="btnImgConfig" href="#"></a> .btnImg { width:100px; height:100px; ...

Unable to perform the 'setSelectionRange' function on the 'HTMLInputElement' due to the input element's type being 'number', which does not allow selection

My attempt to enable text selection in an input box upon user click by using the code snippet below was unsuccessful: <input type="number" onclick="this.setSelectionRange(0, this.value.length)" name="quantity" /> Instead of achieving the desired ef ...

Choose the initial full text that corresponds with a portion of the text

I am currently working on a page with multiple <string> tags containing different strings, like 'Is this a String?  Yes'. My goal is to use JQuery to locate the first instance of 'Is this a String?  ' and extract either ...

Ensure you are focusing on elements exclusively contained within the parent table and not any child tables nested within its cells

Looking for some help with a unique situation here. I'm struggling to find the right selector for this task. For reference, you can check out the jsfiddle at this link: http://jsfiddle.net/NZf6r/1/ The scenario is that I have a parent table containin ...

Out of nowhere, I started getting a 401 error from .net and jquery

My ajax call used to work perfectly: $J.ajax({ type: 'POST', url: "/ajax/getCharts", data: JSON.stringify(cids), dataType: 'json', asynch: false }) However, things changed yesterday. We implemented Microsoft.AspNet ...

"Embracing Flexbox for a fully responsive mobile experience

What's the best way to make this flexbox design responsive for mobile devices? I want the layout to look consistent across both desktop and mobile screens. The issue seems to be related to the responsiveness of the flexbox and the smaller size of mobi ...

Is there a way for me to incorporate a JavaScript file from another JavaScript file in HTML, even if it's just one line below?

It seems that the issue of using a function or a variable from file1 in file2 is not working as expected: <head> <script src="file1.js"></script> <script src="file2.js"></script> </head> Since file2 ...

Incorporating Google fonts into email designs

I am struggling to get Google fonts to display properly in my newsletter emails. Here is the code snippet I have been using: $html=" <html> <style> @import url(http://fonts.googleapis.com/css?family=Lato|Simonetta); </style> <body& ...

Invoking a function using an identifier for modification

I am currently developing a solution, and here is my progress so far: http://jsfiddle.net/k5rh3du0/ My goal is to invoke a function using both the onLoad and onerror attributes with an image. <img src="http://www.etreeblog.com/favicon.ic0" alt="status ...

Is there a way to utilize the Jquery output as a variable in a PHP query?

Here is the code snippet that displays the item clicked using Jquery: <html> <head> <?php include('config/js.php');?> </head> <body> <div id="target"> ...

Enhance your website with an AJAX form integrated with a powerful Website

I need to monitor conversions on a button that is activated by AJAX using visualwebsiteoptimizer's Custom Conversion Goal Code, which consists of generated Javascript code. If I include this code in a PHP file triggered by AJAX, will it execute the j ...