7

If I have a link like this:

<a data-btn="login"></a>

If I wished to select in jQuery using the data attribute which should I do?

var a = $("[data-btn='login']");  //This?

var a = $("[data-btn=login]");    //Or this?
BoltClock
  • 700,868
  • 160
  • 1,392
  • 1,356
C.J.
  • 6,789
  • 7
  • 36
  • 45

3 Answers3

10

As of jQuery 1.5, both approaches will work, and function identically.

jQuery used to require quotes around attribute values, so your second selector won't work with previous versions. If you're stuck with an older version for some reason, use the first selector.

BoltClock
  • 700,868
  • 160
  • 1,392
  • 1,356
  • Is one considered a better practice than the other? Does CSS support both as well? – C.J. Apr 03 '12 at 04:23
  • 1
    @C.J.: I use quotes with all my attribute selectors so I don't run into trouble with special characters otherwise. This is important when it comes to CSS, and I believe it applies to jQuery as well. I'm actually in the process of writing a question-and-answer detailing the differences between jQuery and CSS selectors - maybe I should get that done and post it. – BoltClock Apr 03 '12 at 04:25
  • @BobStein-VisiBone: The "both" in my original answer was intended to mean "both using quotes and not using quotes" as shown in the question, not "both single and double quotes". – BoltClock Aug 27 '16 at 15:59
  • Stand corrected. (I had both-quote issues on the brain.) Anyway the new link explains both both's (with and without, single and double). – Bob Stein Aug 27 '16 at 16:08
2

Even in jQuery 1.5+ I still use quotes, as sometimes it doesn't work without them.

Eugene Retunsky
  • 13,009
  • 4
  • 52
  • 55
2

Funny, I use this syntax:

var a = $('[data-btn="login"]');

which stems from my years in PHP where (and this could open a huge can of worms) using double quotes is arguably slower because it's open to interpreting variables within them whereas single quote strings are not - so I use single quotes more often than not.

I also use single quotes primarily in JavaScript because it's often mixed with HTML which, technically, should have all attribute values surrounded in double quotes, not single quotes and using single quotes saves me from having to escape quotes.

BoltClock
  • 700,868
  • 160
  • 1,392
  • 1,356
Eli Sand
  • 1,032
  • 7
  • 11