Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is document.querySelector not working on pseudo element?

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?

like image 212
Gildas.Tambo Avatar asked Sep 29 '14 08:09

Gildas.Tambo


People also ask

How to use queryselector in document?

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 ...

How to solve the “failed to execute “queryselector on “document” error?

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.

Why are my CSS pseudo-elements not working?

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.

Why is my queryselector method not working?

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.


1 Answers

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

like image 170
Winchestro Avatar answered Sep 28 '22 12:09

Winchestro