I am playing with pseudo elements and javascript but some how i can not style it using javascript.
var div = document.querySelector(":before");
div.style["display"] ="none";
div{
width:200px;
height:200px;
background:red;
position:relative;
}
div:before{
position:absolute;
content:'';
top:0;
right:-100px;
width:100px;
height:100%;
background:green;
}
<div></div>
do anyone knows why this is not working?
The Document method querySelector () returns the first Element within the document that matches the specified selector, or group of selectors. If no matches are found, null is returned. Note: The matching is done using depth-first pre-order traversal of the document's nodes starting with the first element in the document's markup ...
To solve the "Failed to execute 'querySelector' on 'Document'" error pass the entire attribute to the querySelector method or update the identifier of your DOM element to not start with a digit. This example shows how we can pass the entire attribute to the querySelector to avoid changing the id of the DOM element.
The syntax of the specified selectors is invalid. If the specified selector matches an ID that is incorrectly used more than once in the document, the first element with that ID is returned. CSS pseudo-elements will never return any elements, as specified in the Selectors API.
To solve the error, make sure that the class name or ID you're passing to the querySelector method does not start with a digit. Here's an example of how the error occurs.
If you want to style pseudo elements from javascript you have to use the CSSOM to inject the rules. It's not trivial, but it's possible.
var sheet = document.styleSheets[0]; //get style sheet somehow
var rules = sheet.rules;
sheet.insertRule('div:before { display: none; }', rules.length);
a slightly modified example from this article
CCSOM Reference
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With