Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why doesn't this jquery selector with a period work

I have a div with an ID

<div id="updates-pane-user.followed_on">

this jquery selector works

$("[id^='updates-pane']")

but this doesn't

$("#updates-pane-user.followed_on")

I don't see what is wrong.. id names can include periods right? Am I missing something obvious?

like image 855
Nick Ginanto Avatar asked Feb 07 '13 14:02

Nick Ginanto


People also ask

What is a valid jQuery selector?

jQuery selectors are used to "find" (or select) HTML elements based on their name, id, classes, types, attributes, values of attributes and much more. It's based on the existing CSS Selectors, and in addition, it has some own custom selectors. All selectors in jQuery start with the dollar sign and parentheses: $().

What does $() return in jQuery?

$() does not return the jQuery function, (which is $ itself,) but returns a wrapped set, with all those helpful methods on it.

Are all CSS selectors compatible with jQuery?

Starting from jQuery 1.9, virtually all selectors in the level 3 standard are supported by Sizzle (its underlying selector library), with the following exceptions: jQuery cannot select any pseudo-elements as they are CSS-based abstractions of the document tree that can't be expressed through the DOM.


2 Answers

In the latter selector, . is used to denote a class. So it's looking for the .followed_on class, which it obviously doesn't find and so nothing is matched.

In order to fix this, I think you should escape the dot with a double-backslash:

$("#updates-pane-user\\.followed_on")

According to the jQuery docs:

To use any of the meta-characters ( such as !"#$%&'()*+,./:;<=>?@[]^`{|}~ ) as a literal part of a name, it must be escaped with with two backslashes: \\. For example, an element with id="foo.bar", can use the selector $("#foo\\.bar").

In general, try not to use periods or other special characters in your IDs to avoid confusion all around. "Allowed" is not the same as "good practice."

like image 78
Jimbo Avatar answered Oct 12 '22 14:10

Jimbo


Because of the dot in the id attribute which in jQuery syntax represents class selector. This selector is equivalent to selecting node as:

<div id="updates-pane-user" class="followed_on">

like image 22
kidwon Avatar answered Oct 12 '22 14:10

kidwon