What is the difference in jQuery selectors?

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

  • $('.menu')
  • $('menu')
  • $('#menu')

Can someone clarify in which scenario (s) each will be used?

+6
source share
7 answers
  • $('.menu') ... select items with class='menu'

  • $('menu') ..... select <menu /> items

  • $('#menu') ... select an item with id='menu'

+13
source

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

2nd finds <menu></menu>

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

Please note that these rules apply and are based on CSS.

+5
source

$ ('. menu'): the entire item with the class menu

$ ('menu'): entire menu item

$ ('# menu'): item with menu id

+3
source
 $('.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 
+2
source

Class selector (".class")
Selects all elements with the specified class.

Element selector ("element")
Selects all elements with the specified tag name.

ID Selector ("#id")
Selects one element with the given id attribute.


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

+2
source

The jQuery syntax syntax is the same as the css syntax. Thus, ".menu" will select everything with a menu class, "#menu" will select an object with a menu identifier (there should be only one menu, "" will try to select menu items of types.

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 
+2
source

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
source

Source: https://habr.com/ru/post/898686/


All Articles