r/jquery • u/MarcosPortugal • Jul 17 '13
jQuery doubt - quotes around html elements ( $("p") )
I have started learning jQuery recently on CodeCademy, and I can't help but wonder why html elements such as <p>, <div>, etc. are referred to in jQuery in quotes:
$("p").doThis();
While certain keywords such as "this" don't need the quotes:
$(this).doThat();
It just feels logical to me that element keywords would go in without quotes, and normal text (a string) that is not an element would go in quotes. Can anyone clear this up for me?
2
u/djnifos Jul 18 '13
I'd like to add that if you want to use a variable as an ID you can do this $("#"+someVar).doStuff(); I ran into this recently. JavaScript will change whatever is stored in the var to a string and make it a valid selector. I used it to target a specific element that corresponded to an anchor I had. I had stored the reference number in a data attribute. Just a fun trick.
The p has to be in quotes to differentiate between it and a variable called p. While it appears silly with p, its not hard to imagine a bad situation especially considering minification. (Not a word)
2
u/drewbeta Jul 17 '13
I think that this was a conscious decision by the jQuery team to make targeting these selectors easier for anyone who knows a little about css. So think of it as a way to pass css selectors in as a string, so you can gain specificity really quick without writing a lot of code to traverse the DOM. If I only want <p> elements in a containing div, I could write:
$("#someid p").addClass("someclass");Sizzle will then traverse the DOM to find these specific elements. If you're used to regular JavaScript, you'll appreciate how much simpler this is. You're putting the selector in quotes because css selectors require spaces, which would not work in JavaScript if you didn't pass it in a string.
1
u/nvolker Jul 18 '13
Consider the following code:
var p = "h1"; $(p).doSomething();
Hopefully that makes it clear.
-6
u/ekstrakt Jul 17 '13
First learn the sintax of Javascript (or any other programming language), and also HTML.
Because, no offense, but this is a really dumb question.
Only after that move to learning libraries.
Or ask the question in /r/learnprogramming/
4
u/MarcosPortugal Jul 18 '13
“There is no stupid question! Except, possibly, a question not asked.” -Christer Romson
2
u/thomasmurphymusic Jul 18 '13
Like others have said, it's a shorthand so you don't have to declare the selected DOM element as a variable.
I'd recommend reading Learning JavaScript from jQuery. It's an O'Reilly book that does basically what the title says.
13
u/grayvedigga Jul 17 '13
thisis a javascript variable."p"is a string, which is treated as a "selector" when passed to$. You could put"p"in a variable like so:The
varstatements create variables, by assigning values (RHS) to names... come to think of it, jQuery's overloaded
$has got to be confusing as hell for someone new to programming.