jQuery Introduction | Selecting Elements | CSS Selectors
Selecting with CSS Selectors
In jQuery, you can select HTML elements using CSS selectors.
Selecting by Tag Name
You can select all HTML elements by the tag name of an element.
This works the same way as JavaScript’s getElementsByTagName() method.
In the example below, when <button> is clicked, the text of the <span> tag is set to a size of 30px.
$("button").on("click", function() {
$("span").css("fontSize", "30px");
});
Arguments passed to the
$()function must be passed as strings using quotation marks ("").
Selecting by ID
You can also select a specific HTML element by the element’s ID.
This works the same way as JavaScript’s getElementsById() method.
In the example below, when <button> is clicked, the text whose ID is devkuma is set to a size of 30px.
$("button").on("click", function() {
$("#devkuma").css("fontSize", "30px");
});
Selecting by Class
You can select all HTML elements that share the same class.
This works the same way as JavaScript’s getElementsByClassName() method.
In the example below, when <button> is clicked, the text whose class is devkuma is set to a size of 30px.
$("button").on("click", function() {
$(".devkuma").css("fontSize", "30px");
});
Other Selections
You can also select specific HTML elements by attributes and various CSS selectors.
In the example below, when the element whose ID is btn1 is clicked, the text whose title attribute is devkuma is set to a size of 30px.
$("#btn1").on("click", function() {
$("span[title=devkuma]").css("fontSize", "30px");
});
In the example below, when the element whose ID is btn2 is clicked, the text of btn2 itself is set to a size of 30px.
$("#btn2").on("click", function() {
$(this).css("fontSize", "30px");
});
In the example below, when the element whose ID is btn3 is clicked, the text of the first <li> item is set to a size of 30px.
$("#btn3").on("click", function() {
$("ul li:first").css("color", "red");
});