0

How can I change the CSS property ::before in JavaScript?

My CSS code looks like this:

#all-address::before
{
    content: '';
    height: 20px;       
    background: linear-gradient(to bottom, transparent 0%, white 45%, white   100%);
    z-index: 3;
    display: none;
}

Now I want change display: none to display: block with help of JavaScript.

I tried this code but it doesn't seem to work:

var div = document.getElementById("all-address");
div.pseudoStyle("before", "display", "block");
Azametzin
  • 5,223
  • 12
  • 28
  • 46
zharf pzh
  • 75
  • 1
  • 8

2 Answers2

0

No, you cannot access :before or :after from javascript, because they are not a part of the DOM. However you can still achieve your goal by using CSS classes. Example:

<script>
    document.getElementById('abc').className += "minus";
</script>

<style>
    #all-address:before {
        display: none;
    }
    #all-address.minus:before {
        display: block;
    }
</style>
ManUtopiK
  • 4,495
  • 3
  • 38
  • 52
-3

Try some think like this:

  window.getComputedStyle(
        document.querySelector('#all-address'), ':before'
    ).display='block';
alexey
  • 783
  • 1
  • 7
  • 19
  • 1
    Chrome gives `Uncaught NoModificationAllowedError: Failed to execute 'setProperty' on 'CSSStyleDeclaration': These styles are computed, and therefore the 'display' property is read-only` when using this. – Peter B Sep 05 '19 at 14:06
  • Will throw error: `Uncaught DOMException: Failed to execute 'setProperty' on 'CSSStyleDeclaration': These styles are computed, and therefore the 'display' property is read-only.` – ManUtopiK Sep 05 '19 at 14:06
  • Try new version. (property instead of method) – alexey Sep 05 '19 at 14:27