What is the best way to add data-content to hr:after using JavaScript?

Adding style to an element in javascript can be simple. For example:

myElement.style.color = "red";

However, what if I wanted to achieve something like this:

hr:after {
  content: "myRuntimeValue"
}

Is there a way to do this using javascript?

Answer №1

One way to achieve this is by using the element's attribute:

Cascading Style Sheets (CSS)

p#my-id::after {
    // Use the value of an attribute as content for the pseudo-element
    content: attr(data-value);
}

JavaScript (JS)

const specificElement = document.getElementById('my-id');
specificElement.setAttribute('data-value', 'newValueAtRuntime');

Answer №2

:before and :after pseudo-elements are not considered actual DOM elements, therefore they cannot be manipulated directly using JavaScript.

However, a workaround is to create two separate classes with different content and styles, then toggle between them using JavaScript:

Check out this JsFiddle for an example

document.getElementById('demo').addEventListener('click', function(){
        this.classList.remove('demo');
        this.classList.add('New-demo');
      });
.demo:after {
        content: "myRuntimeValue";
        color: orange;
      }
      .New-demo:after {
        content: "Some New Content!";
        color: red;
      }
<p id="demo" class="demo">Click Me!</p>

By utilizing this technique, not only can you modify the content displayed, but also apply specific styles to these pseudo-elements.

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

Numerous buttons activating a single modal component

I have an array called videos, which contains objects of the type Video (defined below). My goal is to create a functionality where clicking on a specific video button opens a modal containing information about that particular video. interface VideosInfo ...

Organize group data by month in a visually appealing table using HTML/PHP with

I have successfully implemented a code that prints HTML table rows from a database table and sorts them by date. The challenge lies in the fact that the date is stored as VARCHAR (due to a pre-existing project with an active database used in a PHP web app ...

Error: Angular is encountering an issue with accessing the property 'push' as it is currently undefined

I have successfully created a news ticker that works well in my codepen example. However, I am encountering an issue with integrating it into my code structure. The error message I am currently receiving is: Cannot read property 'push' of undefi ...

"Encountering a challenge when trying to fetch the value of an undefined or null

When it comes to validating the delivery date entered, I have implemented the following code to ensure it is not earlier than the current date... I have utilized custom validation using jQuery... Here is my model: [UIHint("Date")] [DeliveryDateC ...

Tips for evenly distributing these cards

Check out the full code on Codepen.io <div class="card-container"> <div class="card col-lg-4 col-sm-6 col-xs-12"> <div class="side">Jimmy Eat World</div> <div class="side back"><img ...

Aligning text fields and text areas is not consistent

Seeking a solution to align two input fields side by side, with a textarea directly below them form ul { list-style: none; text-align: center; } form ul li { display: inline-block; margin-left: auto; margin-right: auto; } #nameform, #emailform ...

React modules imported in ES6 not functioning as anticipated

I'm currently facing a problem when trying to import a react class into a container. The structure of my files is as follows: ├── components │ ├── Header │ │ ├── Header.js │ │ └── index.js │ └── ...

Tips on pairing elements from a ngFor processed list with another list using ngIf

If we have a list such as the one shown below: elements = [ { id: 1, name: "one" }, { id: 3, name: "three" }, { id: 5, name: "five" }, { id: 6, name: "six" }, ]; lists = [ { id: 5, name: "five" }, { id: 9, ...

Adjust the text area to automatically expand or shrink based on the text it contains

Is there a way to automatically adjust the size of a textarea based on its content? Here is the code I am currently using for this purpose: var element = document.getElementById(event.target.id); var content = $(this).val().trim(); if (content == "") { ...

The MVC 5 view is unable to display an HTML image when adding it within an appended div

Currently, I am working with ASP.net MVC5 at a novice level. I'm faced with the challenge of creating a div that displays an image using a JavaScript function. Here is the code snippet I have: function showLoadingImage() { $('#submit_Em ...

Stop the infiltration of emotions into your style

Utilizing the JsonForms React Component to dynamically generate an HTML form in my web application. The framework I am using handles all view rendering on the server side. To integrate this component, I compiled a small react component by running npm run b ...

Encountering an Ajax Issue with Laravel 5.4

I encountered the following error: "{"status":"error","msg":"Category was not created"}" Below is my Controller Function where I execute the action : function create_category(Request $request){ if($request->ajax()){ $c ...

Unable to access the attributes of the mongoose model

I'm experiencing an issue with my mongoose model.find code below Displayed here is my node.js code that utilizes mongoose to interact with MongoDB. However, upon running it, I encounter the following error message: Starting... (node:7863) Unhandl ...

Creating a classification for a higher order function

In the code snippet below, I have a controller that acts as a higher order method: const CourseController = { createCourse: ({ CourseService }) => async (httpRequest) => { const course = await CourseService.doCreateCourse(httpRequest. ...

What could be causing the position-sticky feature to malfunction within a nested nav on Bootstrap version 5.3.1?

I'm in the process of developing a user-friendly dashboard that incorporates Bootstrap 5.3.1's nested nav feature. However, I've encountered a problem where the navigation disappears when there is too much content on the page. To address thi ...

Utilizing ScrollView Component in React Native

I have developed a simple app that displays a collection of images with titles, resembling a film gallery where all available films can be viewed. However, I encountered an issue when trying to implement the ScrollView element as it does not allow for scro ...

How can I prevent the expansion of elements in a drop-down menu when using display:

I've been struggling to implement a drop-down feature in my menu. The issue is that when I use display: flex, hovering over the drop-down also expands all other boxes without drop-downs. Any ideas on how to fix this easily? Additionally, is there a w ...

Problem encountered with a selection menu

I'm experiencing some trouble with the dropdown menu. Whenever I try to move the mouse to access the dropdown menu, it seems unresponsive. I attempted adjusting the padding on a line of code but ended up moving the entire line instead. Here is the cod ...

A single pledge fulfilled in two distinct ways

My code ended up with a promise that raised some questions. Is it acceptable to resolve one condition with the token string value (resolve(token)), while resolving another condition with a promise of type Promise<string>: resolve(resultPromise); con ...

Troubleshooting ng-class functionality in AngularJS

I am attempting to utilize AngularJS in order to change the class name of a div element. Despite following the guidance provided in this answer, I am encountering difficulties as the class name is not updating in my view. Below is the code from my view: ...