1

I am trying to select a class with a specific attribute in JavaScript, as below:

var me = document.querySelector('.tab-content[data-tab=1]');

But getting the following error:

Uncaught DOMException: Failed to execute 'querySelector' on 'Document': '.tab-content[data-tab=1]' is not a valid selector.

I tried to change it to jQuery:

$('.tab-content[data-tab=1]')

Then it will work.

I tried to change it by adding double quotes:

var me = document.querySelector('.tab-content[data-tab="1"]');

Then it will also work.

I checked the attribute selector at W3 Schools and in its samples, there are [target=_blank], which does not require double quotes.

So why does removing double quotes not work for JavaScript?

kmoser
  • 8,780
  • 3
  • 24
  • 40
alancc
  • 487
  • 2
  • 24
  • 68
  • 1
    does this answer the question? https://stackoverflow.com/questions/6247221/css-selectors-cannot-match-numerical-attribute-values-why – ProDec Oct 27 '21 at 06:02
  • @ProGu, Yes, it answers half ot eh question. Another half is why jQuery works with the selector? – alancc Oct 27 '21 at 09:36
  • 1
    amazing it works with jQuery, jQuery [documentation](https://api.jquery.com/category/selectors/attribute-selectors/) *Attribute values in selector expressions **must** follow the rules for W3C CSS selectors; in general, that means anything other than a [valid identifier](https://www.w3.org/TR/CSS21/syndata.html#value-def-identifier) should be surrounded by quotation marks.* – ProDec Oct 27 '21 at 09:53
  • @ProGu, Thank you very much for providing the document. I think jQuery is designed to more error torrents. – alancc Oct 27 '21 at 20:52

0 Answers0