← Back to jQuery Course | Chapter 2: Selectors | Lesson 1 of 10

Basic Selectors

ID selectors target one element by its ID.

Select by ID

An ID selector uses a hash symbol followed by the element's id attribute to select exactly one matching element on the page. Because ids must be unique, this is the most direct and fastest way to target a specific element.

Example: Select by ID

javascript
<!DOCTYPE html>
<html>
  <head>
    <script src="https://code.jquery.com/jquery-3.7.1.min.js"></script>
  </head>
  <body>
    <h1 id="title">Page Title</h1>
    <script>
      console.log($("#title").length);
    </script>
  </body>
</html>

Select by Class

A class selector uses a dot followed by the class name, and because many elements can share one class, it returns a jQuery object wrapping every match -- ideal for styling or updating a whole group at once.

Example: Select by Class

javascript
<!DOCTYPE html>
<html>
  <head>
    <script src="https://code.jquery.com/jquery-3.7.1.min.js"></script>
  </head>
  <body>
    <p class="highlight">A</p><p class="highlight">B</p>
    <script>
      console.log($(".highlight").length);
    </script>
  </body>
</html>

Select by Element

An element (tag) selector, like $(p), matches every element with that tag name on the page, which is useful for broad, page-wide changes but can accidentally catch more elements than you intended.

Example: Select by Element

javascript
<!DOCTYPE html>
<html>
  <head>
    <script src="https://code.jquery.com/jquery-3.7.1.min.js"></script>
  </head>
  <body>
    <p>One</p><p>Two</p>
    <script>
      console.log($("p").length);
    </script>
  </body>
</html>

Combine Selectors

Separating selectors with a comma, like $('h1, .highlight'), lets you target multiple unrelated groups of elements in a single call instead of writing several separate statements.

Example: Combine Selectors

javascript
<!DOCTYPE html>
<html>
  <head>
    <script src="https://code.jquery.com/jquery-3.7.1.min.js"></script>
  </head>
  <body>
    <h1>Title</h1>
    <p class="highlight">Text</p>
    <script>
      console.log($("h1, .highlight").length);
    </script>
  </body>
</html>

Use a Selector Variable

Storing a selector string in a variable before passing it to $() keeps your code DRY when you need to reuse the same target in several places, and makes it easy to update the selector in one spot later.

Example: Use a Selector Variable

javascript
<!DOCTYPE html>
<html>
  <head>
    <script src="https://code.jquery.com/jquery-3.7.1.min.js"></script>
  </head>
  <body>
    <p class="item">Item</p>
    <script>
      var sel = ".item";
      console.log($(sel).length);
      $(sel).css("color", "teal");
    </script>
  </body>
</html>

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.