Retrieve the truncated text content from the text node using ellipsis

Is there a way to retrieve truncated text from a node using Javascript? Take a look at the code snippet below:

console.log(document.getElementById("text1").textContent);
// prints "This is a long text"


console.log(document.getElementById("text2").textContent);
// prints "This is a long text as well"
// expected "This is a long text a..."
.longtext {
    width: 140px;
    overflow: hidden;
    white-space: nowrap;
    text-overflow: ellipsis;
}
<div id="text1">This is a long text</div>
<div class="longtext" id="text2">This is a long text as well</div>

I am looking for a solution to obtain the desired "This is a long text a..." from the element with id text2.

Answer №1

I stumbled upon a similar question: How can I access the actual text that is displayed in a DIV when using CSS style overflow: hidden?

To summarize:

There is no straightforward solution. The process involves calculating the visible text in the DIV based on factors such as div size, font size, font type, and text offset within the div.

For implementing ellipsis through JavaScript, check out this link:

Answer №2

Your code snippet has been tested and it is functioning as expected. The 'text-overflow: ellipsis' property is working as intended. Feel free to check out the updated code on JSFiddle by clicking here.

If you are encountering any issues, please provide more details so that I can assist you better. You can also try running the following code and let me know if it resolves your problem:

<html>
<head>Ellipsis</head>
<style>
       .longtext {
           width: 140px;
           overflow: hidden;
           white-space: nowrap;
           text-overflow: ellipsis;
        }
    </style>
    <body>
        <div id="text1">This is a long text</div>
        <div class="longtext" id="text2">This is a long text as well</div>  
    </body>
</html>

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

Issues are arising post-deployment despite JavaScript being enabled in the browser, including a <noscript

Upon deployment, an error appeared in the network tab stating: We're sorry but app-frontend doesn't work properly without JavaScript enabled. Please enable it to continue. Here is the code snippet from the index.html file of a vueJS app: <bo ...

Why is it difficult to parse out a single object using jQuery .each, while multiple objects work perfectly?

Currently, I am dealing with a .each loop that processes an object retrieved from a JSON feed through Ajax (Type: jsonp; the success function sends the "data" to the function/method containing the .each loop). The issue puzzling me is that when the feed r ...

Retrieve Vuejs template by either module or ID

In my .Vue file, I have defined a template along with its subcomponents with the intention of allowing customers to override this template without needing to modify any javascript code. If there exists an element with id="search-result", then that element ...

The continuous loop is triggered when attempting to pass array data from the API

Hello, I have been searching for a solution to my current issue without much success. The problem revolves around retrieving dates from Firebase and populating them into UI elements in my Vue app. My end goal is to align each date with the corresponding mo ...

What is the regular expression that allows numbers between 1 and 24, including decimals?

Can anyone help me create a regex expression that only allows numbers between 1 and 24, with up to 2 decimal places? The numbers should range from 1 to 24, as well as include decimals like 1.00, 1.01, 1.02, all the way up to 24.99. ...

Creating a responsive Image for desktop screens with the help of Tailwind and nextJS

I'm currently working on a component that displays a set of images with horizontal scroll. The challenge I'm facing is setting different dimensions for mobile/tablet screens and desktop screens. For mobile and tablet, I want the images to be disp ...

What are the steps to integrating databases with HTML5?

I currently have SPA applications developed with angularjs, but I am in need of creating an installer that allows users to work offline using a secure local database. I experimented with IndexedDB and converted my SPA into a Chrome extension, however, I di ...

Adjusting Text Width in fabric.js: A How-To Guide

In my experience, I have found that setting textAlign for a fabric.js Text object seems to be ineffective because the textfield's width is automatically adjusted to fit the text perfectly. I searched through the API but couldn't find any way to ...

"Encountering issues with getStaticPaths not generating any paths

I have a folder named data which contains a file called events.ts: export const EventsData: Event[] = [ { name: 'School-Uniform-Distribution', images: ['/community/conferences/react-foo.png', "/community/conferences/react ...

Issue with Accessing Subdomain Cookies on Express Backend Using CORS and Cookie-Parser

I am currently tackling a challenge in my MERN (MongoDB, Express, React, Node.js) application related to receiving cookies from subdomains in my Express backend. Despite implementing CORS and cookie handling successfully for a simple localhost origin, I am ...

`AngularJs Controller Unit Testing with sweetalert Integration in Jasmine Framework`

When it comes to testing angularjs controllers with jasmine and karma, there seems to be an issue with testing codeblocks within the sweetalert function. How can I verify that the sweet function is being called from my test class in order to test whether $ ...

Ways to correct the issue of double animation effect while utilizing the $(window).scroll function?

Currently, I am facing an issue where the elements in viewport trigger the animation twice when the user scrolls. This strange behavior only occurs when the page is loaded at the very top and then scrolled down. If the page is loaded anywhere else, everyth ...

What are the steps to styling a component with CSS Emotion?

I am facing an issue with using a theme with TypeScript in this component const buttonDisabled = css` color: ${({ theme }) => theme.color}; `; Is there a way to correctly type this component? Error: No overload matches this call. Overload 1 of 2, & ...

Specify the width of one element to always be the same as the width of another

One common challenge is maintaining the width of one element equal to another when the page loads (refer to link description here). However, it becomes tricky when the side width changes, such as resizing the browser window. Is there a way to dynamically ...

Tips on sending arguments to functions associated with ...mapActions...()?

After analyzing the passage below export default { methods: { ...mapActions(["updateData", "resetData"]); } } I wanted to include a parameter in the called functions. Unsure of the proper way to do this while still using the ...mapAction() call, ...

The Bootstrap select feature does not override the original dropdown menu; instead, it adds its own functionality alongside it

I have implemented a select combo using this library. After adding the necessary CSS and JS files, I encountered the following result. Here is what I have attempted so far: <link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.mi ...

Sometimes, the browser may fail to recognize a jQuery click event when a CSS3 transform is applied

There is an issue where click events are sometimes not triggered when an element contains another element being animated with CSS transitions. To see an example of this problem, check out the test case at http://codepen.io/anon/pen/gbosy In my layout, I ...

Animate your SVG with CSS using hover effects that originate from the center of the SVG

I successfully implemented this animation using GSAP and you can view the Codepen for reference: https://codepen.io/whitelionx/full/vYGQqBZ const svgs = document.querySelectorAll("svg"); svgs.forEach((svg) => { const tl = gsap .timelin ...

Using Selenium in Python to interact with radio buttons that are not traditional input type radio buttons

I am facing a challenge with Selenium where I need to click on a radio button that appears to be an image instead of a standard input radio button. Specifically, I am trying to figure out how to click on triggerControl2, which is the top button used to act ...

Adjusting the overflow of a parent div based on the position of the div within it by scrolling

I'm trying to create a page with 3 different sections: <div class="container" id="main-container"> <div class="section" id="profile"> Hello World </div> <div class="section" id="projects"> Hello World 2 ...