Selecting elements
Find elements with CSS selectors, jQuery filters, and work on many elements at once.
jQuery uses CSS selectors
If you can select it in CSS, you can select it in jQuery. Put the selector in quotes inside $( ).
| Selector | Selects |
|---|---|
| $('p') | Every <p> |
| $('#title') | The element with id="title" |
| $('.card') | Every element with class="card" |
| $('ul li') | Every <li> inside a <ul> |
| $('input[type=email]') | Inputs with type="email" |
| $('h2, h3') | Every <h2> and <h3> |
One line changes many elements
<ul>
<li class="done">HTML</li>
<li>CSS</li>
<li class="done">JavaScript</li>
<li>jQuery</li>
</ul>
<button id="mark">Highlight finished courses</button>
<script>
$(function () {
$('#mark').on('click', function () {
$('li.done').css('color', 'green'); // every matching element at once
$('li').first().css('font-weight', 'bold');
});
});
</script>
There is no loop: jQuery applies .css() to every element it found. This is called implicit iteration.
Handy filters
| Code | Gives |
|---|---|
| $('li').first() | The first item |
| $('li').last() | The last item |
| $('li').eq(2) | The third item (counting from 0) |
| $('li').length | How many were found |
| $('li:even') | Items 0, 2, 4... |
| $('li').not('.done') | Items without class done |
Exercise
Make every even row of the table light grey and print how many rows there are into #count.
<table>
<tr><td>Ada</td></tr>
<tr><td>Tunde</td></tr>
<tr><td>Kemi</td></tr>
<tr><td>Chidi</td></tr>
</table>
<p id="count"></p>
<script>
$(function () {
});
</script>
Show a possible solution
<table>
<tr><td>Ada</td></tr>
<tr><td>Tunde</td></tr>
<tr><td>Kemi</td></tr>
<tr><td>Chidi</td></tr>
</table>
<p id="count"></p>
<script>
$(function () {
$('tr:even').css('background', '#eee');
$('#count').text($('tr').length + ' rows');
});
</script>
Check your understanding
Quick check
What does $('.menu a') select?
Why: A descendant selector, like CSS.
Quick check
$('li').eq(0) is...
Why: eq counts from 0.
Quick check
How do you check how many elements were found?
Why: .length.