jQuery Selectors

Objectives

  • Select elements with $()
  • Use .css() to style elements

Selecting with jQuery

$("selectorGoesHere")

Selecting with jQuery is very similar to querySelectorAll, in that we provide a CSS style selector and jQuery will return all matching elements

Selecting with jQuery

$("selectorGoesHere")

//to select all img tags
$("img")  

//to select all elements with class 'sale'
$(".sale") 

//to select element with id "bonus"
$("#bonus") 

//to select all a tags inside of li's
$("li a")  

We select and then manipulate

Manipulating Style

.css(property, value)

The .css() method is jQuery's interface to styling. 

$(selector)

Manipulating Style

.css(property, value)

//select elem with id "special" and give it a border
$("#special").css("border", "2px solid red");


//we can also pass in an object with styles
 var styles = {
    backgroundColor : "pink",
    fontWeight: "bold"
 };

$("#special").css(styles);

We select and then manipulate

Manipulating Style

.css(property, value)

//select all li's and make them yellow
$("li").css("color", "yellow");

//select all elements with class "big"
//and give them an orange border
$(".big").css("border", "1px dashed orange");


We can style multiple elements at once

Exercise

<div>Div 1</div>
<div class="highlight">Div 2</div>
<div id="third">Div 3</div>
<div class="highlight">Div 4</div>
  • Correctly include jQuery
  • Select all divs and give them a purple background
  • Select the divs with class "highlight" and make them 200px wide
  • Select the div with id "third" and give it a orange border
  • Bonus: Select the first div only and change its font color to pink

Use the following starter HTML:

Printer Friendly - jQuery Selectors

By Colt Steele

Printer Friendly - jQuery Selectors

  • 1,713