开发者

What's the Difference in jQuery Selectors?

开发者 https://www.devze.com 2023-04-11 13:06 出处:网络
Here\'s a list of selectors I\'ve seen before: $(开发者_StackOverflow\'.menu\') $(\'menu\') $(\'#menu\')

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

  1. $(开发者_StackOverflow'.menu')
  2. $('menu')
  3. $('#menu')

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


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

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

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


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.


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

$('menu'): all menu element

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


$('.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


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/


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


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.
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号