skip to Main Content

I want to set a Max length of 60 characters in titles, using pure JavaScript. But it does not want to work.

Here is the html

<div class="limiter">
Pandemic deaths are spiraling 
out of control since the 
opening of the country 
and now we test the limiter
</div>

Here is the JavaScript

document.querySelector(".limiter").each(function () {
  var a = 60;
  var b = document.querySelector(this).text();
  if (b.length > a) {
    document.querySelector(this).text(b.substring(0, a + 1) + " ...");
  } else {
    document.querySelector(this).text(b);
  }
});

Any idea why it does not work ?

2

Answers


  1. Refer here to learn more Ref: stackoverflow.com/q/9329446/125981

    /* one way */
    /*
    const limiters = document.querySelectorAll(".limiter");
    limiters.forEach(function (element) {
      const a = 60;
      let b = element.textContent;
      if (b.length > a) {
        element.textContent = (b.substring(0, a + 1) + " ...");
      }
      console.log(b, element.textContent);
    });
    */
    
    /* another way */ 
    const limiters = document.querySelectorAll(".limiter");
    for(const el of limiters) {
      const a = 60;
      if (el.textContent.length > a) {
        el.textContent = (el.textContent.substring(0, a + 1) + " ...");
      }
    }
    <div class="limiter">
    Pandemic deaths are spiraling 
    out of control since the 
    opening of the country 
    and now we test the limiter
    </div>
    Login or Signup to reply.
  2. It looks like you’re moving from jQuery to vanilla JavaScript. You’ll notice that the code isn’t transferable. The code looks similar but the syntax is different.

    Updating your code:

    1. To pick up an array-like list of nodes you’ll need to use querySelectorAll.

    2. each should become forEach. Note there are a few other methods for iterating over the node list but forEach is the closest match for your use-case. The first argument in its callback is the current iterated element.

    3. JavaScript doesn’t have a text() function. You need to get/set the textContent property directly. (Or innerText depending on your needs – here you can see the differences between the two).

    4. You need one condition – to change the text if its length exceeds the limit you’ve imposed. In this example I’ve used slice and a template string to create the new truncated string.

    5. These days its better to move on from var and use const or let to declare your variables.

    // Set the limit
    const limit = 60;
    
    // Grab all the elements with a "limiter" class
    // The callback's first argument "el" is the current
    // iterated element
    document.querySelectorAll('.limiter').forEach(el => {
    
      // For convenience assign the text content of the current
      // iterated element to a variable called "text",
      // and trim the beginning/end whitespace it
      const text = el.textContent.trim();
    
      // If the text length is greater than the limit
      // set the element's text content to the truncated content
      if (text.length > limit) {
        el.textContent = `${text.slice(0, limit + 1)}...`;
      }
    });
    body > * ~ * { margin-top: 0.5rem; }
    <div class="limiter">
      Pandemic deaths are spiraling out of control since the opening of the country and now we test the limiter
    </div>
    <div class="limiter">
      Lions and Tigers and Bears, Oh My!
    </div>
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search