Search code examples
jquerycssjquery-selectorscss-selectors

Attribute selectors with or without quotes?


Does it matter which way the following selector is written? It validates both ways and the W3C spec seems silent on the issue of quotation marks.

Option 1:

input[type=text]

Option 2:

input[type='text']

I've seen selectors that work both with and without quotes. Do both ways always work for either CSS or jQuery?

So, is using the quotation marks simply a matter of preference? Semantics? CSS version?

Do we have two methods because of backward compatibility? If so, which way is best going forward?

Despite the accepted answer to this other SO question, I'm thinking quotes is best:

input[type='text']

Solution

  • I'd sum it up this way:

    • For some sequences of characters (legal identifiers), you don't need quotes.
    • For all other sequences of characters (like anything that starts with a number), you must use quotes.
    • If you KNOW what constitutes a legal CSS identifier and that's what you have, you can leave off the quotes.
    • If you KNOW that what you have is not an identifier, you must put in the quotes.
    • If you don't want to think about it and want to do it consistently all the time, use the quotes.

    For [type=text], you can leave off the quotes if you want to because text is a legal CSS identifier.

    I personally prefer consistency and not having to think about it and less of a chance of making a mistake so I always put in the quotes.