Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why this is not a valid CSS selector using querySelectorAll in JS? [duplicate]

Tags:

javascript

css

I'm trying to find in my DOM all the img elements with 2x class using Vanilla JS. I'm using the querySelectorAll method like this:

document.querySelectorAll('img.2x');

But it throws this error at the console log:

Uncaught DOMException: Failed to execute 'querySelectorAll' on 'Document':
'img.2x' is not a valid selector.

Why img.2x is not a valid selector? Thanks.

like image 388
Elias Garcia Avatar asked Mar 22 '17 19:03

Elias Garcia


1 Answers

While it certainly does look valid, you'll need to explicitly escape any digits that begin a CSS class in order to use it within your selector:

document.querySelectorAll('img.\\2x');
like image 141
Rion Williams Avatar answered Oct 31 '22 04:10

Rion Williams