7

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.

Elias Garcia
  • 6,772
  • 11
  • 34
  • 62
  • 6
    Class selectors can't start with a number, unless you escape it. `"img.\\2x"` –  Mar 22 '17 at 19:39
  • 1
    Class names cannot begin with a digit. See https://www.w3.org/TR/html/dom.html#classes – haim770 Mar 22 '17 at 19:39
  • Another duplicate: http://stackoverflow.com/questions/4089006/can-xhtml-and-html-class-attributes-value-start-with-a-number#4089056 – rockerest Mar 22 '17 at 19:42

1 Answers1

7

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');
Rion Williams
  • 74,820
  • 37
  • 200
  • 327
  • Ahhh okay! I have used the W3C HTML validator and it doesn't throw any error. This only happens with JS right but it's valid to have a class starting with a number in the HTML right? – Elias Garcia Mar 22 '17 at 19:42