I am trying to make a click handler in jQuery that changes the color of an ‘eyebrow’ element above a Heading element. I know that pseudo elements are not part of the actual DOM, but the way that this is set up in my project has this element set with a pseudo element and I am having trouble figuring out a way to get the color of the eyebrow to change when I click the heading. Any ideas would be greatly appreciated.
codepen: https://codepen.io/jon424/pen/poVYPzr
jQuery(function() {
changeColor()
});
function changeColor() {
$('#main').on("click", function() {
$('.main__heading:before').css("background-color", "red");
})
}
.padding {
border : 1px solid red;
padding : 40px;
}
#main:hover {
cursor : pointer;
}
.main__heading:before {
align-items : baseline;
background-color : green;
content : "";
display : flex;
height : 5px;
left : 0;
top : 0;
width : 70px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="padding">
<div class="main__heading">
<h1 type="button" id="main">Heading Text</h1>
</div>
</div>
2
Answers
You can use css variables…
As you mentioned, you can’t manipulate
:before
, because it’s not technically part of the DOM and therefore is inaccessible by any JavaScript. But you can add a new class with a new:before
specified.Note: While it’s impossible to directly modify the :before content, there are ways to read and/or override it using JavaScript. See "Manipulating CSS pseudo-elements using jQuery (e.g. :before and :after)" for a comprehensive list of techniques.
Review this revised code block for a working example to solve your issue: