28
Selectors - is a key to understanding jQuery. Generally, it’s combination of CSS 1-3, XPath and custom code. Selectors allow you easy and quick identify any set of webpage elements for manipulating. Selecting the part of document is performed by using function jQuery(). This is the most important function of library. Depending of passed arguments it can do many things. It this post I will use syntax jQuery (element) which wrap jQuery functionality around a single or multiple set of document elements. This function also has alias $(), which make scripts more readable.
So, let’s talk about type of selectors.
Basic selectors.
#id - select single element with the given id.
This code will set red 3-pixels border to div with id=”mydiv”:
$("#mydiv").css("border","3px red"); |
Open this example in new window and view source code.
element - select all elements on page with given name.
This code select all div’s on webpage and set red border around them:
$("div").css("border","3px solid red"); |
Open this example in new window and view source code.
.classname - select all elements with given class.
This code make all elements with class “myheadertext” look in bold:
$(".myheadertext").css("font-weight","bold"); |
Open this example in new window and view source code.
* - select all elements on page.
This code will set red border to all elements on page (including html and body!):
$("*").css("border","3px solid red"); |
Open this example in new window and view source code.
selector1, selector2, selector3, … - select set of selectors.
This code will select 3 divs on page and set padding from top to 10px for them:
$("#div1, #div2, #div3").css("padding-top", "10px"); |
Open this example in new window and view source code.
Hierarchy selectors.
ancestor descendant - select all descendant elements specified by “descendant” of elements specified by “ancestor”.
This code select inputs of given form and set blue dotted border about them:
$("form input").css("border", "2px dotted blue"); |
Open this example in new window and view source code.
parent > child - select all child elements specified by “child” of elements specified by “parent”. Notice that this selector match only direct child elements (first level).
This code select all childs of element with id=”main” and set double red border around them:
$("#main > *").css("border", "3px double red"); |
Open this example in new window and view source code.
prev + next - select all next elements specified by “next” that are next to elements specified by “prev”.
Select all input fileds that are next to label and set their value to “Labeled!” of blue color:
$("label + input").css("color", "blue").val("Labeled!"); |
Open this example in new window and view source code.
prev ~ siblings - select all elements that are siblings after the “prev” element.
Select all divs on the same level after div with id=”prev” and set them blue border:
$("#prev ~ div").css("border", "3px groove blue"); |
Alex
Add A Comment