Testing your skills with some exercises

In this section you’ll practice doing some exercises targeting the selectors and the filters described in this lesson. If you want to test your solutions, you can run them using the jQuery Selectors Lab Page. In addition, we’ll provide you our solutions to allow you to compare them with yours.

Exercises

Here’s the list of exercises:

1.  Select all the links in the page.

2.  Select all the direct child links of a <div> having the class wrapper.

3.  Select all the links and the paragraphs that have as their ancestor a <div>.

4.  Select all the <span>s that have the attribute data-level equal to hard but not the attribute data-completed equal to true.

5.  Select all the elements on the page having the class name wrapper without using the class selector.

6.  Select the third list item inside the list having the ID list, at any level.

7.  Select all the list items (li) inside the list having the ID list, after the second.

8.  Select the paragraphs that are the multiple of 3 plus 1 (1, 4, 7, and so on) child of their parent, having the class description.

9.  Select the <input>s of type password only if they’re required (required attribute of HTML5) and are the first child of a <form>.

10.  Select all the <div>s in the page that have no children, have an odd position (hint: not index!), and don’t have the class wrapper.

11.  Create a custom filter to select elements having only numbers, letters, or the underscore (_) as their text.

Solutions

Here’s the list of solutions:

1.  $('a')

2.  $('div.wrapper > a')

3.  $('div a, div p') or even better, using the context parameter, $('a, p', 'div')

4.  $('span[data-level="hard"][data-completed!="true"]')

5.  $('[class~="wrapper"]')

6.  $('#list li:eq(2)') or even better $('li:eq(2)', '#list')

7.  $('li:gt(1)', '#list')

8.  $('p.description:nth-child(3n+1)')

9.  $('input[required]:password:first-child', 'form')

10.  $('div:empty:even:not(.wrapper)')

11.  

$.expr[“:”].onlyText = $.expr.createPseudo(function(filterParam) {
return function(element, context, isXml) {
return element.innerHTML.match(/^\w+$/);
}
});

How did you do? Do you feel comfortable with the ideas outlined so far? Good! With this section we’ve completed the overview of the selectors available and how you can create your own.


Posted

in

by

Tags:

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *