How do I select an item using class or ID?

jQuery

How do I select an item using class or ID?

This code selects an element with an ID of "myDivId". Since IDs are unique, this expression always selects either zero or one elements depending upon whether or not an element with the specified ID exists.

1
                          
$("#myDivId")

This code selects an element with a class of "myCssClass". Since any number of elements can have the same class, this expression will select any number of elements.

1
                          
$(".myCssClass")

A jQuery object containing the selected element can be assigned to a JavaScript variable like normal:

1
                          
var myDivElement = $("#myDivId");

Usually, elements in a jQuery object are acted on by other jQuery functions:

1
2
3
                          
var myValue = $("#myDivId").val(); // get the value of a form input
$("#myDivId").val("hello world"); // set the value of a form input

Related Articles