Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What's the meaning of the comma in a jQuery selector [duplicate]

<html> <head> <script type="text/javascript" src="jquery.js"></script> </head> <body> <ul>   <li><strong>list</strong> item 1 -     one strong tag</li>   <li><strong>list</strong> item <strong>2</strong> -     two <span>strong tags</span></li>   <li>list item 3</li>   <li>list item 4</li>   <li>list item 5</li>   <li>list item 6</li> </ul>  <script type="text/javascript"> $('li').filter(function(index) {   return $('strong', this).length == 1; }).css('background-color','red'); </script>  </body> </html> 

Given the HTML above, what's the meaning of the comma in the selector below?

return $('strong', this).length == 2; 

What will happen if I remove the word 'strong'?

like image 910
dramasea Avatar asked Dec 28 '10 02:12

dramasea


People also ask

What does a comma do in CSS selector?

The comma in a CSS selector separates multiple selectors within the same styles. For example, let's look at some CSS below. With this syntax, you are saying that you want th tags, td tags, paragraph tags with the class red, and the div tag with the ID firstred all to have the style color red.

What is the meaning of selectors in jQuery?

jQuery selectors allow you to select and manipulate HTML element(s). 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.


1 Answers

It sets this as the context from which the query is performed.

An equivalent (and slightly more efficient) way to write it is:

return $(this).find('strong').length == 2; 

When I say equivalent, I mean behind the scenes, it is actually flipped around into the version above.

If you remove the 'strong', you won't have a valid selector. You'll be doing:

return $(this).find('').length == 2; 

Looks like it just returns an empty jQuery object, which means length will be 0, so you won't get any elements out of the .filter().


Reference:

http://api.jquery.com/jQuery/

jQuery( selector [, context ] )

context

Type: Element or jQuery

A DOM Element, Document, or jQuery to use as context

like image 180
user113716 Avatar answered Oct 05 '22 18:10

user113716