Select an Element by Class or ID with jQuery

jQuery uses the same selectors as CSS for getting elements with class names and ID. A . (dot) represents a class and a # (hash) represents an ID. In this tutorial, we will learn how to use these selectors to get elements and turn them into jQuery objects.

 

Get an Element by ID

The following example demonstrates getting an element by its ID and storing the jQuery object in a variable. This object can then be used to get and set the element text, attributes .etc.

 

<div id="foo"></div>
var elm = $('#foo');

// set the text of the element.
elm.text('Some text.');
<div id="foo">Some text.</div>

 

Get an Element by Class

The same principle works with getting by class except the jQuery object created will affect multiple elements with the same class.

 

<div class="foo"></div>
<div class="foo"></div>
var elm = $('.foo');

// set the text of the elements.
elm.text('Some text.');
<div class="foo">Some text.</div>
<div class="foo">Some text.</div>
jquery