jQuery: Select First Element with Class

To get the first element containing a class with jQuery, use the :first pseudo selector after the class name.

 

To demonstrate this let's create some HTML input elements with a class and focus the cursor on the first one using jQuery.

 

<form action="something" method="post" id="contact">

  <label for="name">Name</label>
  <input type="text" name="name" id="name" class="form-input">

  <label for="age">Age</label>
  <input type="number" name="age" id="age" class="form-input">

  <button type="button" id="submit_contact">Submit</button>
</form>
$('.form-input:first').focus();

 

In the above example, when the page loads the first input field in the form is focused on making it a slightly more ergonomic experience for the user.

jquery