Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Changing pseudo-element style from javascript [duplicate]

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

like image 721
jon Avatar asked Mar 05 '18 08:03

jon


People also ask

How do you change pseudo element?

In general, if we want to change anything in pseudo elements through JavaScript, we do it in the following way: Create CSS classes on element, which will change pseudo elements' UI. Get the element using querySelector. Modify the classes using classList.

Can I have multiple before pseudo elements for the same element?

1, an element can only have at most one of any kind of pseudo-element at any time.

Can you target pseudo element in JavaScript?

Since they're not part of the DOM, CSS pseudo-elements can't be selected and edited with JavaScript the same way as traditional elements on a page.

Can we specify inline styles for pseudo elements?

You can't specify inline styles for pseudo-elements. This is because pseudo-elements, like pseudo-classes (see my answer to this other question), are defined in CSS using selectors as abstractions of the document tree that can't be expressed in HTML.


1 Answers

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.

like image 81
Prashanth KR Avatar answered Oct 21 '22 08:10

Prashanth KR