AbuMariam
AbuMariam

Reputation: 3678

Understanding jQuery Attribute Selector which uses #

Could someone tell me what below jQuery selector will grab (I didn't write it but I need to understand it)...

var $cat = $('a[href="#cat"]');

Is it all the anchor tags which have 'cat' in the value of their href attribute?

Also does using the '$' in the variable name have any significance or effect? Is it bad practice?

Upvotes: 2

Views: 71

Answers (5)

allicarn
allicarn

Reputation: 2919

it will grab something like:

<a href="#cat">This link</a>

but not the following:

<a href="cat">This one</a>
<a href="#dog">This one</a>
<a href="#cattywompus">Another</a>

The [] in a selector are to select elements with a certain attribute. There are similar selectors, for example, you can use for "starts with" ([href^="#cat"]) or "contains" ([href*="#cat"]), but with just the = it means equal to.

See more detail here: https://api.jquery.com/category/selectors/attribute-selectors/

Using $ in the element name is common to indicate that it is a jQuery object or a DOM node, as opposed to another simpler variable (like an integer or array, etc.)

Upvotes: 1

zackkrida
zackkrida

Reputation: 421

$('a[href="#cat"]'); will select any Anchor with a href of '#cat'.

Additionally, $ at the start of a variable name is simply a naming convention. It doesn't serve a specific meaning, but is often used to identify a variable as a JQuery Object.

Upvotes: 0

meskobalazs
meskobalazs

Reputation: 16041

It gets the anchor element with the given anchor value (in this case, this is the cat page anchor).

And no, using $ in the variable name is not bad practice, it shows at once, that it is a jQuery object. Of course if you are also using AngularJS, it is a more gray are, as it uses the same naming convention for its internal objects.

By "not bad practice" I meant, not bad practice per se. So it can be used, but make sure that you use it consistently, because inconstent naming conventions are bad practice.

Upvotes: 3

jpganz18
jpganz18

Reputation: 5858

It will select an A tag which links points to cat, like

<a href="#cat" >Link</a>

$var is a valid practice,is standard js you can say

var $myvar = "hello";
and
var myvar = "hello";
both will work the same

check this link

http://www.bennadel.com/blog/1778-using-variable-in-jquery-code-is-just-hungarian-notation.htm

Upvotes: 1

Chris K.
Chris K.

Reputation: 1078

It will return all elements that look something like

<a href="#cat" ...>...</a>

Upvotes: 1

Related Questions