What's the Difference in jQuery Selectors?

2019-06-20 05:55发布

问题:

Here's a list of selectors I've seen before:

  1. $('.menu')
  2. $('menu')
  3. $('#menu')

Could anyone clarify in what scenario(s) each would be used?

回答1:

  1. $('.menu') ... select elements with class='menu'

  2. $('menu') ..... select <menu /> elements

  3. $('#menu') ... select an element with id='menu'



回答2:

1st finds <div class="menu"></div>

2nd finds <menu></menu>

3rd finds <div id="menu"></div>

Note that these rules applies and are based on CSS.



回答3:

$('.menu'): all element with a class menu

$('menu'): all menu element

$('#menu'): the element with an id of menu



回答4:

$('.menu') -> <div class="menu"></div> or any other tag with class menu
$('menu')  -> <menu></menu>
$('#menu') -> <div id="menu"></div> or any other tag with id menu


回答5:

Class Selector (“.class”)
Selects all elements with the given class.

Element Selector (“element”)
Selects all elements with the given tag name.

ID Selector (“#id”)
Selects a single element with the given id attribute.


Reference: http://api.jquery.com/category/selectors/basic-css-selectors/



回答6:

The jQuery selector syntax is the same as that of css. So ".menu" will select everything with a class of menu, "#menu" will select the object with an id of menu (there should only be one! "menu" will try to select elements of type menu.

An example;

<div class="foo" id="d1">Div 1</div>
<div class="foo" id="d2">Div 2</div>

<span class="foo" id="s1">Span 1</span>
<span class="foo" id="s2">Span 2</span>

$(".foo").css("background", "red"); //sets the background of all 4 elements to red
$("div").css("background", "blue"); //sets the background of the two divs to blue
$("#s1").css("background", "green"); //sets the background of span 1 to green


回答7:

Taken from http://forum.codecall.net/javascript-tutorials/14363-jquery-selectors.html

#id: -> This will match any element with the given ID.

element -> This will match any element supplied.

.class  -> This will match any element with the given class.