Selecting - Exercise

Contact Us or call 1-877-932-8228
Selecting - Exercise

Selecting

Duration: 10 to 20 minutes.

Open the file jqy-concepts/Exercises/index.html in your browser. Use jqy-concepts/Exercises/sandbox.js to accomplish the following:

  1. Select all of the div elements that have a class of 'module'. Add the 'showMe' class to them.
  2. Come up with three selectors that you could use to get the third item in the #myList unordered list. Try each of them using the 'showMe2' class. Which is the best to use? Why?
  3. Select the label for the search input using an attribute selector. Add the 'showMe2' class to it.
  4. Figure out how many elements on the page are hidden (hint: .length). Display in the console.
  5. Figure out how many image elements on the page have an alt attribute. Display in the console.
  6. Select all of the odd table rows in the table body. Add the 'oddRow' class to them.

Solution:

jqy-concepts/Solutions/js/sandbox-selecting.js
$(document).ready(
	function() {

		// Select all of the div elements that have a class of 'module'
		// Add the 'showMe' class to them. 
		$('div.module').addClass('showMe');

		// Three selectors to get the third item in the #myList
		$('#myListItem').addClass('showMe2'); 			
		// above is best -- IDs are always the fastest selector
		// but, would it always be the third item?
		
		$('#myList>li:eq(2)').addClass('showMe2');
		$('#myList>li').eq(2).addClass('showMe2');
		// either would be best if the list item didn't have an ID
		
		$('#myList li:eq(2)').addClass('showMe2');
		$('#myList li').eq(2).addClass('showMe2');
		// not quite as good, since it would allow items from inner lists
		
		// Select the label for the search input using an attribute
		// selector. Add the 'showMe2' class to it. 
		$('label[for=q]').addClass('showMe2');
		
		// Figure out how many elements on the page are hidden
		console.log($(':hidden').length + " hidden");
		// That includes head elements - below shows only elements in body,
		// and also omits script tags in body
		console.log($('body :hidden').not('script').length + " hidden");

		// How many image elements on the page have an alt attribute?
		console.log($('img[alt]').length + " images with alt");
		
		// Select all of the odd table rows in the table body.
		// Add the 'oddRow' class to them.
		$('#fruits>tbody>tr:odd').addClass('oddRow');
		// if you don't specify tbody, you'll get the tr in the thead too
	}
);

An id selector is always the most efficient, since the browser can handle that natively.

The label is tied to the input by the for attribute, so we can use that to find the label.

$('img[alt]') will find any img tag where the alt attribute is present, even though we didn't ask to find any specific value.

Starting the final query with an id enables the jQuery engine to quickly reduce the total number of tags it needs to examine.

Next