I want to inherit the textContent
of a seperate span
element to the content
of an :after
style using Vanilla JavaScript.
As seen below in HTML, the span
with className
span-class, is the element that I want to extract the textContent
from. The div with className
sample, is the parent
of the div
with className
random (which houses span-class), and the p
element for which I want to apply an :after
style, with an inherited content:" ";
.
These elements are repeated throughout the website with the same className
, and hence require an Array as shown below in the Desired Outcome.
HTML
<div class="sample">
<div class="random">
<span class="span-class">example</span>
</div>
<p class="p-text">some random text, some random text, some random text</p>
</div>
<div class="sample">
<div class="random">
<span class="span-class">example2</span>
</div>
<p class="p-text">some random text, some random text, some random text</p>
</div>
CSS
.p-text:after{
content: "text I want to be dynamic";
}
Desired Outcome:
NOTE: I understand that pText:after.content
does not work, however it best characterizes what I want to achieve
var sample = Array.from(document.querySelectorAll(".sample"));
sample.forEach(function(smpl) {
var textContent = smpl.querySelector(".span-class").textContent;
var pText = smpl.querySelector(".p-text");
if (textContent === "example") {
pText:after.content = "example";
} else if (textContent === "example2") {
pText:after.content = "example2";
}
})
ALSO NOTE: Creating another span
element and placing it at the end of the textContent
of .p-text
, although a solution, is not an option.
Thanks in advance for any solutions!