Cut the text within each individual container

For many of you, the question I'm about to ask is quite simple. Take a look at the following HTML code:

<div class="content" id="content">
    <div class="container" id="container">
        <h1>Title</h1>
        <img class="post-img" src="#">
        <p class="text" id="text">Lorem500</p>
        <div class="button"></div>    
    </div>
    <hr>
    <div class="container" id="container">
        <h1>Title</h1>
        <img class="post-img" src="#">
        <p class="text" id="text">Lorem500</p>
        <div class="button"></div>    
    </div>
    <hr>
</div>

The goal is to create multiple "blog posts" with a title, image, brief description, and a "Read more" button. I would like to truncate the "text" to 300 characters using JavaScript. I've attempted using both for and while loops, but as a newbie, I'm struggling to get it right.

var content = document.getElementById('content');

while ( content.length >= 0 ) {
  $('#text').text(function(i, txt) {
    return txt ? txt.slice(0, 300) + " ..." : txt;
  });
}

I know it might seem silly, but I've tried various approaches, and this is the latest one I've come up with.

Your assistance would be greatly appreciated. Thank you for taking the time to read this. Your help means a lot to me.

Answer №1

Avoid using a while or for loop in this scenario as it may lead to an infinite loop due to the constant content length exceeding

Instead, you should utilize an if statement to check if the content size is beyond 300 and then apply the substring method.

var content = "Hello this is some longer text to be cut shorter";
var displayText = ""; 

if(content.length > 5) {
    displayText = content.substring(0, 5);
} else {
    // Content is shorter than 5 characters
}

console.log(displayText) // Output: Hello

In your specific case, you would use content.length > 300 and content.substring(0, 300)

Answer №2

Consider giving this a shot:

let container = document.getElementById('container');
for(let i=0;i<$('.text').length;i++){
  let element = $('.text')[i];
  if(element.innerHTML.length>350){
    element.innerHTML = element.innerHTML.substring(0, 350) + " ...";
  }
}

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

Exploring the possibility of integrating direct search functionality into the URL bar within an Angular application

One interesting feature I observed on GitHub is that after typing "github.com" in the URL bar, you can directly search by pressing the spacebar, which activates the "search mode." Here's how it looks like on Chrome: https://i.sstatic.net/XIgJu.png I ...

Error Message: A key is being provided to the classes property that is not implemented in the current context

Trying to customize Material-UI styles with makeStyles() as outlined in the documentation but encountering a warning when passing a classname in the parent component that is not specified in useStyles. The warning message reads: Warning: Material-UI: th ...

The data from the method in the Vue.js component is not displaying as expected

Currently diving into Vue.JS (2) and exploring the world of components. My current challenge involves using a component within another component, grabbing data from a data method. Here's what I have so far: HTML <div id="root"> <h1> ...

Retrieve the source code of the current page using JavaScript and the Document Object Model (DOM)

Is there a way to retrieve the source of the current page using JavaScript and DOM? Do I need to utilize AJAX for this task? ...

Utilizing Visuals from a Vue Component Collection

As I attempt to publish a Vue library to npmjs, I encounter an issue with the images within it. After publishing the app to NPM and importing it into my main app, everything appears to be working correctly. However, the paths to the images in the library ...

mandatory data fields for an HTML form

I'm having some trouble creating an HTML form with mandatory input fields. The code I have so far is shown below: <div class="col-sm-6"> <label for="city" class="form-control">City ...

Creating a network of communication between API routes in NextJS

Can the fetch API be used within an API route in NextJs? I have a large handler and instead of having everything in one handler, I'd like to modularize it so that after completing a specific task (e.g., writing to a database), I can call another handl ...

Retrieve data from dropdown menu to showcase table using Node.js

I'm currently diving into learning nodejs and mongodb. My backend setup includes expressjs and mongojs, while ejs is handling the frontend of my application. The main goal is to allow users to select a class from a dropdown menu and view a correspondi ...

How can I change the color of a cube in Three.js?

I'm currently working on developing a basic 3D game using three.js. My goal is to create colored cubes, but I'm encountering an issue where all the cubes are displaying the same color. My cube creation code looks like this: var geometry = new ...

Tips for integrating JQuery into a JavaScript file seamlessly without causing conflicts

Similar Question: Dynamically Including jQuery using JavaScript if it's not already present I am currently working on a project that requires users to embed a piece of javascript code on their websites, similar to Google Analytics. My main concer ...

The filtering function stops working after the initial use

As I develop an app using React and Redux, my goal for the following code snippet is to function as a reducer within the main application. I have imported a filterData function, which works seamlessly the first time any Action type is selected. However, it ...

Function for JavaScript Form Validation: Iterating through each element

I have a set of form input elements that need to be iterated through in order to validate them based on their name attributes. I utilized jQuery to accomplish this, using the .each method to loop through the elements and apply/remove a class name to those ...

Creating a Timeless Banner with the Magic of `background:url()`

I have a banner placed within a div tag that displays my banner image. I am trying to create a fading effect when transitioning to the next image, but I am struggling to achieve this. I attempted to use jQuery fadeIn(), however, it did not work as expected ...

I am looking for a string with this particular format in JavaScript

I am working with a JSON string array that looks like this: var dataMaster = [ {"id":1,"name":"John Doe","age":30}, {"id":2,"name":"Jane Smith","age":28} ] If you want to see how I would like to transform this data, please visit the following lin ...

Having trouble displaying the accurate model value in the alert

I have the following piece of code: $(document).ready(function () { var edit= @Model.Edit.ToString().ToLower(); if( edit !=true ) { $("#editWriteup").hide(); } var date= @Model.EndDate; alert(date); ...

Encountering an issue with file uploading in Firebase: Error message indicates that AppCheck is being utilized before activation

I am facing an issue while trying to upload a file to my firebase account. Whenever I attempt this, I encounter the following error message: Uncaught (in promise) FirebaseError: AppCheck: AppCheck is being used before activate() is called for FirebaseApp ...

Troubles arising while using ng serve in Angular 2

I'm currently facing an issue during the installation process of an existing Angular application. When trying to run the application using the ng serve command, I encounter the following error message: The "@angular/compiler-cli" package was not prope ...

One effective way to transfer state to a child component using function-based React

My goal is to pass an uploaded file to a child component in React. Both the parent and child components are function-based and utilize TypeScript and Material-UI. In the Parent component: import React from 'react'; import Child from './ ...

Struggling to add information to a database table with PHP

Check out the code snippet below: Here is the HTML5 code block: <div class="col-md-8 blogger-right-container"> <form action="blogger_account.php" method="post" role="form" enctype="multipart/form-data"> < ...

What causes the disappearance of CSS styles when attempting to modify the className in react js?

I am currently working on a basic react application, and I am trying to dynamically change the name of a div element using the following code snippet - <div className={'changeTab ' + (page.login ? 'leftSide' : 'rightSide')} ...