Search code examples
javascriptjqueryloopsfor-loopmaxlength

Javascript - For Loop for maxLength on P Tag


I have this solution here that limits the characters of the selected P tag to 125 characters, however it only applies to the first child in the loop, how can I edit the following code to work in a For loop? I've attempted some solutions with some jQuery but haven't found any to work.

Appreciate the help!

function truncateText(selector, maxLength) {

    var element = document.querySelector(".hp-um-description")
     for (element = element) {
        var truncated = element.innerText;

        if (truncated.length > maxLength) {
            truncated = truncated.substr(0,maxLength) + '...';
        }
        return truncated;  
     }
    }

    $(".hp-um-description").each(function(){
      document.querySelector('.hp-um-description').innerText = truncateText('.hp-um-description', 125);
    });

Solution

  • You can use jQuery .text() to avoid loops and achieve this quite cleanly.

    function truncateText(selector, maxLength) {
      $(selector).text((i, txt) => txt.length > maxLength ? txt.substr(0,maxLength) + "..." : txt);
    };
    
    truncateText(".hp-um-description", 100);
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <p class="hp-um-description">Lorem ipsum dolor sit amet, consectetur adipiscing elit. Mauris feugiat ipsum massa, et sagittis enim tempus id. Mauris nisl turpis, pellentesque scelerisque congue nec, faucibus vel arcu.</p>
    
    <p class="hp-um-description"> Fusce id ultrices nibh. Suspendisse sit amet felis lobortis, rhoncus ex eu, fringilla lacus.</p>
    
    <p class="hp-um-description">Suspendisse sit amet felis lobortis, rhoncus ex eu, fringilla lacus. Duis vehicula placerat sapien, ac consectetur dolor egestas eget.</p>

    The code above will loop through all elements satisfied by the selector and apply a function. This line detemines if it should be truncated or not:

         txt.length > maxLength ?    txt.substr(0,maxLength) + "..."     :         txt
    //(If length exceeds maxlength)     (truncate and add ...)         (else)    (leave the text as-is)
    

    If you'd like to be able to truncate string values as well, you can use the code below instead:

    String.prototype.truncate = function(maxLength) {
      var t = this.toString();
      return t.length > maxLength ? t.substr(0, maxLength) + "..." : t;
    };
    
    function truncateText(selector, maxLength) {
      $(selector).text((i, txt) => txt.truncate(maxLength));
    };
    
    //Truncate an existing element's text
    truncateText(".hp-um-description", 100);
    
    //Truncate a string
    console.log("This is a long string that exceeds 30 characters.".truncate(30));
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <p class="hp-um-description">Lorem ipsum dolor sit amet, consectetur adipiscing elit. Mauris feugiat ipsum massa, et sagittis enim tempus id. Mauris nisl turpis, pellentesque scelerisque congue nec, faucibus vel arcu.</p>
    
    <p class="hp-um-description"> Fusce id ultrices nibh. Suspendisse sit amet felis lobortis, rhoncus ex eu, fringilla lacus.</p>
    
    <p class="hp-um-description">Suspendisse sit amet felis lobortis, rhoncus ex eu, fringilla lacus. Duis vehicula placerat sapien, ac consectetur dolor egestas eget.</p>