Where to Start with jQuery Selectors

jQuery uses the same selectors as CSS. This makes it very easy to select the elements you want to work with. The two most commonly used selectors are id and class. So before we start make sure you have your jQuery setup and the $(document).ready() function on the page.

Selecting by ID

This is best used when you want to target one specific element. The selector is exactly the same as what you would use to set styles for the particular element in CSS.

Selecting element with CSS and setting some styles.

#youridhere {
	display: none;
}

Now selecting the same element with jQuery and adding CSS styles.

$("#youridhere").css("display","none");

Selecting by Class

With the class selector you can select multiple elements at once. jQuery deals with multiple elements in a very simple manor. It returns an array of jQuery objects. With the way jQuery is designed it will automaticaly apply anything you do to your selection to all elements without having to loop threw the results.

Lets take a simples example of hiding all elements with a class of hide. To do this with CSS we would create the class in our style sheet like so:

.hide {
	display: none;
}

To do this same thing to all the elements with the class of hide in jQuery. You would use the following statement:

$(".hide").css("display","none");

This should get you started on the path of using jQuery in your projects. To read more about the selectors your can use in jQuery check out the documentation.

2 Comments

  1. DeathfireD on September 10, 2009 at 3:50 pm

    Just in case anyone was wondering, here’s an example of how to add multiple styles to an element.

    $(“#youridhere”).css(“color”,”#000000″).css(“font-size”,”15px”);



    • DeathfireD on October 13, 2009 at 9:20 am

      Since Josh didn’t edit my first

      $(‘#yourid’).css({“color”:”#000000″, “font-size”:”12px”});