Using CSS Only
Utilizing CSS, you have the ability to define the content of pseudo elements (::before
and ::after
) as shown below:
.my-class::before {
content: "I am some unique text!";
}
By leveraging the CSS function attr()
, you can populate the pseudo element's content with an attribute from your element:
.my-class::before {
content: attr(data-text);
}
It is important to note that if you add extra text within the element's content tag like
<span class="my-class" data-text="Some Text">Hello, I am different Content!</span>
it will be displayed as
Some TextHello, I am different Content!
Utilizing JavaScript
To access a DomElement using JavaScript, you can choose from methods like document.getElementById
, document.getElementsByClassName
, document.querySelector
, and document.querySelectorAll
.
Then, retrieve the data-text
attribute through HtmlElement.getAttribute
and insert it as a string into the element's textContent
:
const element = document.querySelector('.my-class');
element.textContent = element.getAttribute('data-text');