What's the Difference in jQuery Selectors?

2019-06-20 05:33发布

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?

7条回答
祖国的老花朵
2楼-- · 2019-06-20 05:53

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
查看更多
爷的心禁止访问
3楼-- · 2019-06-20 05:58

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

$('menu'): all menu element

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

查看更多
淡お忘
4楼-- · 2019-06-20 06:02
  1. $('.menu') ... select elements with class='menu'

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

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

查看更多
干净又极端
5楼-- · 2019-06-20 06:02

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.

查看更多
做个烂人
6楼-- · 2019-06-20 06:04

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/

查看更多
何必那么认真
7楼-- · 2019-06-20 06:05

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.
查看更多
登录 后发表回答