Search code examples
javascriptcssdompseudo-element

Changing pseudo-element style from javascript


How I can change CSS for a pseudo element style?


I am trying to get the CSS before:: rule and change left: to 95% or 4px. How can I perform this in my context?

I've also made some test using document.querySelector but it doesn't work, I get a compute Read-Only error.

Do you have suggestions?


Example:

css

.iziToast-wrapper-bottomLeft .iziToast.iziToast-balloon:before {
  border-right: 15px solid transparent;
  border-left: 0 solid transparent;
  right: auto;
  left: 8px;
}

js

    if(description_iziToast){
        let RightMode = event.x>window.innerWidth/2;
        let bubblePosition = document.getElementsByClassName("iziToast-balloon")[0]; // get the div that hold the bubble
        let ajustScreenLR = RightMode && document.getElementsByClassName("iziToast")[0].offsetWidth || 0; // halfScreen ajustement
        //bubblePosition.style.left = RightMode && '95%' || '4px'; // here i need to change the position in the befor:: attribut
        description_iziToast.style.left = `${event.x-20-ajustScreenLR}px`; 
        description_iziToast.style.top = `${event.y-105}px`;
    }
    }else{
        if(description_iziToast){ iziToast.destroy(); description_iziToast = false; };
    }

Here the app console debug

enter image description here

enter image description here


Solution

  • Since pseudo-elements do not exist in the DOM, they cannot be accessed in Javascript. The workaround is to create a <span> instead of using :before and the same logic has to be applied.