How to show hidden pseudo-element with JavaScript

940 Views Asked by At

I'm using CSS to hide form elements:

#main_form #form-field-email, #form-field-realtor_select { display: none;}
#main_form .elementor-select-wrapper::before { display: none; }

Then JavaScript to show them with:

document.getElementById("form-field-first_name").onclick = function(){
document.getElementById('form-field-email').style.display = 'block';
document.getElementById('form-field-realtor_select').style.display = 'block';

The problem is with the pseudo-element .elementor-select-wrapper::before which is needed to hide the down arrow in the select element. I need to get the arrow to display using the JavaScript onclick event. I tried document.getElementsByClassName() but that did not work.

You can see the test page here: Test Page. Click First Name or Last Name to reveal fields (more than listed above) and you'll see the down arrow is mission from the select element.

2

There are 2 best solutions below

5
Ross Gatih On BEST ANSWER

So, it's not possible to select a pseudo element directly, but you can create a set of CSS styles like the following, which will change the ::before element using a "toggleable" class on the parent:

#main_form .elementor-select-wrapper::before {
    display: none;
}

#main_form .elementor-select-wrapper.show-chevron::before {
    display: block;
}

When you add (or remove) the .show-chevron class to .elementor-select-wrapper, it should toggle the ::before element.

document.getElementsByClassName('elementor-select-wrapper')[0].classList.add('show-chevron')

Let me know if this works! If not, I can take another look

0
lortschi On

It is possible to edit the css pseudo elements via JS, as the following snippet shows.

    // Create a new style element
    var styleElement = document.createElement("style")
    document.head.appendChild(styleElement)

    // Get the CSSStyleSheet object of the newly created style element
    var styleSheet = styleElement.sheet

    // Add a new rule targeting the :after pseudo-element
    styleSheet.insertRule(".your-class-name:after { display: none; }", 0)