Tips for clearing out text in a <p> tag with javascript when it exceeds a specific length of 100 characters

Is there a way to automatically truncate text to (...) when it exceeds 100 characters inside a paragraph with the class .class?

For instance, if I have a long paragraph like this:

<div class='classname'>
 <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Duis nibh velit, suscipit bibendum sagittis non, consequat vestibulum ante. Praesent in fermentum turpis. Nam nec erat vulputate, imperdiet mi ac, porttitor diam. Quisque posuere odio vel nulla varius dictum. Vestibulum malesuada tellus id cursus pretium. Cras volutpat, diam vel molestie bibendum, neque risus ullamcorper augue, vel convallis odio purus hendrerit quam. Mauris convallis dolor vel ex placerat, non imperdiet dolor lacinia. </p>

Desired Outcome:

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Duis nibh velit, suscipit bibendum sagittis non, consequat ...

Answer №1

let peles = document.querySelectorAll('.classname > p')
for(p of peles){
  let txt = p.innerText
  txt = txt.replace(txt.substring(100),'...')
  p.innerText = txt
}
<div class='classname'>
 <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Duis nibh velit, suscipit bibendum sagittis non, consequat vestibulum ante. Praesent in fermentum turpis. Nam nec erat vulputate, imperdiet mi ac, porttitor diam. Quisque posuere odio vel nulla varius dictum. Vestibulum malesuada tellus id cursus pretium. Cras volutpat, diam vel molestie bibendum, neque risus ullamcorper augue, vel convallis odio purus hendrerit quam. Mauris convallis dolor vel ex placerat, non imperdiet dolor lacinia. </p>
<div>

Answer №2

// Select all paragraphs within elements with class: classname
const paras = document.querySelectorAll(".classname > p");
paras.forEach( p => {
    const text = p.textContent;
    if (text.length > 100){
        const newText = text.slice(0, 100) + " ...";
    p.textContent = newText;
}
})
<div class='classname'>
 <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Duis nibh velit, suscipit bibendum sagittis non, consequat vestibulum ante. Praesent in fermentum turpis. Nam nec erat vulputate, imperdiet mi ac, porttitor diam. Quisque posuere odio vel nulla varius dictum. Vestibulum malesuada tellus id cursus pretium. Cras volutpat, diam vel molestie bibendum, neque risus ullamcorper augue, vel convallis odio purus hendrerit quam. Mauris convallis dolor vel ex placerat, non imperdiet dolor lacinia. </p>
 <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Duis nibh velit, suscipit bibendum sagittis non, consequat vestibulum ante. Praesent in fermentum turpis. Nam nec erat vulputate, imperdiet mi ac, porttitor diam. Quisque posuere odio vel nulla varius dictum. Vestibulum malesuada tellus id cursus pretium. Cras volutpat, diam vel molestie bibendum, neque risus ullamcorper augue, vel convallis odio purus hendrerit quam. Mauris convallis dolor vel ex placerat, non imperdiet dolor lacinia. </p>
</div>

UPDATE: Addressing query from the comments

const parasExceptFirst = document.querySelectorAll(".classname p:not(:first-child)");

parasExceptFirst.forEach( p => {
  p.remove()
})
<div class='classname'>
 <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Duis nibh velit, suscipit bibendum sagittis non, consequat vestibulum ante. Praesent in fermentum turpis. Nam nec erat vulputate, imperdiet mi ac, porttitor diam. Quisque posuere odio vel nulla varius dictum. Vestibulum malesuada tellus id cursus pretium. Cras volutpat, diam vel molestie bibendum, neque risus ullamcorper augue, vel convallis odio purus hendrerit quam. Mauris convallis dolor vel ex placerat, non imperdiet dolor lacinia. </p>
 <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Duis nibh velit, suscipit bibendum sagittis non, consequat vestibulum ante. Praesent in fermentum turpis. Nam nec erat vulputate, imperdiet mi ac, porttitor diam. Quisque posuere odio vel nulla varius dictum. Vestibulum malesuada tellus id cursus pretium. Cras volutpat, diam vel molestie bibendum, neque risus ullamcorper augue, vel convallis odio purus hendrerit quam. Mauris convallis dolor vel ex placerat, non imperdiet dolor lacinia. </p>
</div>

Answer №3

Give this a shot

$(document).ready(function() {
    // Adjust these variables as needed.
    var showChar = 100;  // Set default character limit
    var ellipsestext = "...";
    

    $('.more').each(function() {
        var content = $(this).html();
 
        if(content.length > showChar) {
 
            var c = content.substr(0, showChar);
            var h = content.substr(showChar, content.length - showChar);
 
            var html = c + '<span class="moreellipses">' + ellipsestext+ '&nbsp;</span><span class="morecontent"><span>' + h + '</span>&nbsp;&nbsp;<a href="" class="morelink">' + moretext + '</a></span>';
 
            $(this).html(html);
        }
 
    });
 
    $(".morelink").click(function(){
        if($(this).hasClass("less")) {
            $(this).removeClass("less");
            $(this).html(moretext);
        } else {
            $(this).addClass("less");
            $(this).html(lesstext);
        }
        $(this).parent().prev().toggle();
        $(this).prev().toggle();
        return false;
    });
});

Answer №4

If you want to enhance the layout, consider using CSS, such as the following approach:

display: -webkit-box;
overflow: hidden;
-webkit-line-clamp: 2;
-webkit-box-orient: vertical;
line-height: 1.5;

Implementing this method may provide a more refined user experience.

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

Angular 14 captures typed form data as `<any>` instead of the actual data types

On the latest version of Angular (version 14), I'm experiencing issues with strictly typed reactive forms that are not functioning as expected. The form initialization takes place within the ngOnInit using the injected FormBuilder. public form!: For ...

What is the definition of the term "WebapiError"?

I'm currently developing a Spotify Web App that focuses on retrieving the top albums of KD Rusha using the Client ID and Artist ID to exclusively fetch his releases on Spotify. To accomplish this, I am utilizing an npm package called spotify-web-api-n ...

Update the var value based on the specific image being switched using jQuery

I have implemented a jQuery function that successfully swaps images when clicked. However, I am now looking to enhance this functionality by passing a parameter using $.get depending on the image being displayed. Here is the scenario: I have multiple comm ...

What is the best way to get rid of trailing numbers in material UI class names?

The standard class for the material ui input box is .MuiInputBase-input, but when I inspect it using developer tools, I see that the same class is displayed as .MuiInputBase-input-619. How can I remove the suffix from the class name? I am currently utili ...

Partially translucent electron window

Is there a way in Electron to create a view similar to the finder in macOS, where the sidebar is opaque and the main content is not? https://i.stack.imgur.com/UKXg2.jpg I am aware of how to make an entire window opaque, but I'm unsure if it's p ...

Why does my chart.js disappear every time I perform a new render?

Hey there, I'm facing an issue with my code. Let me paste what I have... import React, { memo, useEffect } from 'react'; import Chart from "chart.js"; /* redux-hook */ import { useSelector } from 'react-redux' const lineChart = m ...

Nested ng-repeats within ng-repeats

I have a question regarding the correct way to utilize an inner ng-repeat inside of an outer ng-repeat: Essentially, I am looking to implement something along these lines: <tr ng-repeat="milestone in order.milestones"> <td>{{mi ...

Designing an intricate layout with the help of Bootstrap-Vue

After exploring the Vue-Bootstrap panel in my previous question, I implemented the following code snippet to generate a panel: <b-card no-body class="mb-1"> <b-card-header header-tag="header" class="p-1" role="tab"> <b-button b ...

When clicking on the dress in the masque, how do I change the attire so that it is instantly applied to the masque?

$("#tail").kendoFlatColorPicker({ preview: false, value: "#000", change: select }); $("#head").kendoFlatColorPicker({ preview: false, value: "#e15613", change: select }); I implemented the color ...

Display the tooltip only when the checkbox is disabled in AngularJS

My current setup includes a checkbox that is disabled based on a scope variable in Angular. If the scope variable is true, the checkbox stays disabled. However, if the scope variable is false, the checkbox becomes enabled. I am looking to implement a too ...

The Vue2 @click event does not function properly when using v-html within a different component

I currently have a sign up form that includes an Alert component for displaying any errors. One of the conditions may prompt a message saying "You already have an account, click here to log in". The error messages are passed as props to the "Alert" compon ...

Morris.js tutorial: Enhancing bar charts with data labels

I have this: https://i.sstatic.net/GXjur.png But I want this instead: https://i.sstatic.net/spcS2.png Does morris.js support this feature? If not, what would be the most effective method to implement it? ...

Is it possible for a JSON array to consist of objects with varying key/value pairs?

Is it possible for a JSON array to contain objects with different key/value pairs? The example provided in this tutorial shows objects within the JSON array having the same key/value pair: { "example": [ { "firstName": " ...

managing information through the elimination of nested keys with node js / javascript

let json=[ { metadata: { tags: [] }, sys: { space: { sys: [Object] }, id: '4gSSbjCFEorYXqrgDIP2FA', type: 'Entry', }, fields: { richTextEditor: { 'fn-US': [Object] }, short: { 'as-ds': &a ...

bootstrap thumbnail displayed without a border

I have decided to incorporate Bootstrap into my latest project: <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS ...

Align select and number inputs vertically in Firefox

How can I achieve vertical alignment for these inputs on Firefox? The alignment works perfectly in Chrome, Safari, and Opera, but not in Firefox (Version 57 tested on macOS, Windows, and Linux Mint). While removing type="number" from the input resolves th ...

gathering identical objects in the collection

I need to calculate the total time of the specified objects and display it in a single list. Here is the object data: var list = [ { 'user': 'Tom', time: 270547 }, { 'user': 'Alex', time: 82081 }, { 'user&apo ...

Is it necessary to verify user input in a registration form using PHP?

I currently do not have any code to share, as the issue at hand is not directly related to coding. However, I am interested in verifying certain aspects of user input, such as ensuring a phone number entered in a registration form is limited to 8 digits an ...

Obtain the string value for the template variable

Trying to display a string literal if element.elementId is null or undefined. <div>{{String(element.elementId)}}</div> Encountering an error: TableBasicExample.html:6 ERROR TypeError: _co.String is not a function at Object.eval [as updat ...

Ways to minimize the space between elements in a flex container

My goal is to minimize the space between my images that expand on hover. I aim for it to resemble this: expectation However, the current appearance is more like this: reality This is what I currently have: .container { display: flex; width: 100 ...