7

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

vsync
  • 118,978
  • 58
  • 307
  • 400
jon
  • 1,494
  • 3
  • 16
  • 29
  • 1
    If it is really just to switch about two fixed values, then simply add a 'rightMode' class on the element, and in css do `elem.rightMode::before { left: 95%;}` – Kaiido Mar 05 '18 at 08:57
  • I wanted to avoid modifying the original css code in the event of an update need. I will probably proceed in this way. – jon Mar 05 '18 at 09:01

2 Answers2

15

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.

connexo
  • 53,704
  • 14
  • 91
  • 128
Prashanth KR
  • 294
  • 2
  • 8
  • In my case I've created one new class that actually overwrites the pseudo-elements (both the ::before and ::after). For example we want to rewrite the color then do `.pseudo-update::before, .pseudo-update::after { color: #efefef }` and then just add your class using JavaScript to the element you want to update `document.querySelector('.menu-btn-burger').classList.add('pseudo-update');` – Tom Danilov Sep 24 '21 at 12:24
11

Here are two ways to directly manipulate a pseudo-element:

1 - Using some sort of style manager

This "manager" is an object with methods which allows easier manipulation of CSS rules on-the-fly, so here is a very basic example which you can study and implement for your specific needs:

var elm = document.querySelector('main');

// Reference: https://stackoverflow.com/a/28930990/104380
var styleManager = (function() {
    // Create the <style> tag
    var style = document.createElement("style")

    // WebKit hack
    style.appendChild(document.createTextNode(""));

    // Add the <style> element to the page
    document.head.appendChild(style);
    
    function getStyleRuleIndexBySelector(selector, prop){
      var result = [], i,
          value = (prop ? selector + "{" + prop + "}" : selector).replace(/\s/g, ''), // remove whitespaces
          s = prop ? "cssText" : "selectorText";

      for( i=0; i < style.sheet.cssRules.length; i++ )
        if( style.sheet.cssRules[i][s].replace(/\s/g, '') == value)
          result.push(i);

      return result;
    };

    return {
      style : style,
      
      getStyleRuleIndexBySelector : getStyleRuleIndexBySelector,
      
      add(prop, value){
        return style.sheet.insertRule(`${prop}{${value}}`, style.sheet.cssRules.length);
      },
      
      remove(selector, prop){
        var indexes = getStyleRuleIndexBySelector(selector, prop), i = indexes.length;
        
        // reversed iteration so indexes won't change after deletion for each iteration
        for( ; i-- ; )
          style.sheet.deleteRule( indexes[i] );
      }
    }
})();


elm.addEventListener('mouseenter', function(){
   // each new rule should be added the END of the sheet
   styleManager.add('main::before','left:90%; top:60%;');
   styleManager.add('main::before','left:70%;');
});

elm.addEventListener('mouseleave', function(){
  styleManager.remove('main::before', 'left:70%;');  // you can also try without the "left:70%;" part
});
main{  
  position:relative;
  width: 200px;
  height: 200px;
  border: 1px dashed silver;
}

main::before{
  content: 'pseudo';
  width: 100px;
  height: 100px;
  background: lightgreen;
  position: absolute;
  left: 10px;
  top: 40px;
  
  transition:.3s ease-out;
}
<main>Hover &amp; out</main>

2 - With CSS variables:

var elm = document.querySelector('main');

elm.addEventListener('mouseenter', function(){
   elm.style.setProperty('--before-left', '90%');
});

elm.addEventListener('mouseleave', function(){
  elm.style.setProperty('--before-left', '10px');
});
main{  
  --before-left : 10px; /* <-- Your CSS should use variables for this to work */
  
  position:relative;
  width: 200px;
  height: 200px;
  border: 1px dashed silver;
}

main::before{
  content: 'pseudo';
  width: 100px;
  height: 100px;
  background: lightgreen;
  position: absolute;
  left: var(--before-left); /* <-- using the variable */
  top: 40px;

  transition:.3s ease-out;
}
<main>Hover &amp; out</main>
vsync
  • 118,978
  • 58
  • 307
  • 400