Selecting elements

Lesson 2 of 12 15 min read Free lesson

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 $( ).

SelectorSelects
$('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

HTML Try it in CodeLab
<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

CodeGives
$('li').first()The first item
$('li').last()The last item
$('li').eq(2)The third item (counting from 0)
$('li').lengthHow 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.

Starting code Try it in CodeLab
<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
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?

Quick check

$('li').eq(0) is...

Quick check

How do you check how many elements were found?

Hi there! đź‘‹ Have a question about the courses or joining the class? Ask me.