Selectors in jQuery
Selectors in jQuery
Element Selector
Select elements by tag name.
Example: "p" - Selects all
elements.
$(document).ready(function() {
$("#testbutton").click(function() {
$("p").css("background-color","red");
});
});
Multiple Selector
Select multiple elements by separating selectors with comas.
Example: "div, strong, #testbutton" - Selects all
elements, elements, and the element (the Test button) since its ID attribute is set to testbutton.
$(document).ready(function() {
$("#testbutton").click(function() {
$("div, strong, #testbutton").css("background-color","red");
});
});
All Selector
Select all elements by using an asterisk.
Example: "*" - Selects all elements.
$(document).ready(function() {
$("#testbutton").click(function() {
$("*").css("background-color","red");
});
});
Child Selector
Selects a child element by using the following syntax. "parent > child".
Example: "div > p" - Selects all
elements that are children of
elements.
$(document).ready(function() {
$("#testbutton").click(function() {
$("div > p").css("background-color","red");
});
});
First Child Selector
Selects first child elements by using the syntax :first-child.
Example: "div > p:first-child" - Selects all
elements that are first children of
elements.
$(document).ready(function() {
$("#testbutton").click(function() {
$("div > p:first-child").css("background-color","red");
});
});
Last Child Selector
Selects last child elements by using the syntax :last-child.
Example: "div > p:last-child" - Selects all
elements that are last children of
elements.
$(document).ready(function() {
$("#testbutton").click(function() {
$("div > p:last-child").css("background-color","red");
});
});
Descendant Selector
Selects a descendant element by using the following syntax. "ancestor descendant".
Example: "div strong" - Selects all elements that are descendants of
elements.
$(document).ready(function() {
$("#testbutton").click(function() {
$("div strong").css("background-color","red");
});
});
Even Selector
Selects matched elements based on their position. Even positioned elements are selected using the following syntax. :even.
Example: "p:even" - Selects the first and third
elements.
$(document).ready(function() {
$("#testbutton").click(function() {
$("p:even").css("background-color","red");
});
});
Odd Selector
Selects matched elements based on their position. Odd positioned elements are selected using the following syntax. :odd.
Example: "p:odd" - Selects the second and fourth
elements.
$(document).ready(function() {
$("#testbutton").click(function() {
$("p:odd").css("background-color","red");
});
});
