In most implementations of jQuery, the shortcut $() is used instead of jQuery() to keep the code concise.
Caution: Certain other JavaScript libraries also use the $() function, so conflicts may occur when attempting to use multiple libraries simultaneously. jQuery provides a fix for this situation with jQuery.noConflict(). For more information, see http://docs.jquery.com/Core/jQuery.noConflict.
Selecting DOM Elements Using CSS Syntax
In this article, we will use firefox for developer as demo environment, you can click the wrench icon in the right top, and click “web developer tool”.
You will see another pane at the bottom of the browser, Then click console, and you can type the snippet demonstrated below:
Basic Selectors
Selecting Elements by Tag Type
To select an element by tag type, simply use the name of the tag (such as p, div, or span) as your selector.
To select all paragraph (<p>) tags in our test document, enter the following snippet at the bottom of the console:
$("p");
Press Enter and the code will execute. If you have multiple result, then point to one of them, the browser will highlight the related part.
Selecting Tags by Class Name, ID
Just as quickly as you can select by tag type, you can select elements by their assigned class or classes.
The syntax for this is the use the class name preceded by a period (.):
.class
Select all the elements with the class foo by executing the following snippet in the console:
$(".foo");
To select an element by its id attribute, the CSS syntax of the id preceded by a hash sign (#) is used.
#id
Match all elements with an ID of bar with the following:
$("#bar");
Combining selectors
In some situations, it may be necessary to isolate only certain tags that correspond to a class, which is easy to do by combining tag type and class in your selector.
Enter the following in the console to select only paragraph tags with the class foo:
$("p.foo");
Hierarchy Selectors
Sometimes, it’s not enough to be able to select by element, class, or ID. There are points at which you’ll need to access elements contained within, next to, or after another element.
Selecting Descendant Elements
Selecting descendant elements, which are elements contained within other elements, is done using the ancestor selector followed by a space and the descendant selector.
ancestor descendent
$("body span");
This will find all spans contained within the body tag (<body>) of the document, even though the spans may be also inside paragraph tags.
Very next level descendent
Only the very next level of element is considered for matching.
$("body>span");
Selecting Next Elements
Occasionally in a script, you’ll need to select the next element in the DOM. This is accomplished by providing an identifier for the starting element (any selector pattern works here), followed by a plus sign (+), followed by the selector to match the next instance of:
$(".foo+p");
There is only one element with the class foo, so only one paragraph element p.first is returned:
<div class="foo"> Lorem ipsum is placeholder text commonly used in the graphic, print, and publishing industries for previewing layouts and visual mockups. </div> <p class="first"> Lorem ipsum is placeholder text commonly used in the graphic, print, and publishing industries for previewing layouts and visual mockups. </p> <p class="second"> Lorem ipsum is placeholder text commonly used in the graphic, print, and publishing industries for previewing layouts and visual mockups. </p>
Selecting Sibling Elements
Sibling elements are any elements contained within the same element. Selecting sibling elements works similarly to selecting next elements, except the sibling selector will match all sibling elements after the starting element, rather than just the next one.
To select sibling elements, use the starting element selector, followed by an equivalency sign (~), and the selector to match sibling elements with:
start~siblings
To match all siblings after the paragraph with class foo, execute the following command in the console:
$(“.foo~p”);
The result set will be:
p.first, p.second
Basic Filters
Filters are another very powerful method of accessing elements in the DOM. Instead of relying on element types, classes, or IDs, you’re able to find elements based on their position, current state, or other variables, such as the first child, last child, odd number.
The basic syntax of a filter is a colon (:) followed by the filter name:
:filter
Selecting First or Last Elements
One of the most common uses of filters is to determine if an element is the first or last element in a set.
With filters, finding the first or last element is incredibly simple; just append the filter :first or :last to any selector:
$("p:last");
This returns the following when executed in the console:
>>> $("p:last");
[ p#bar ]
Selecting Elements that Do Not Match a Selector
If you need to find all elements that don’t match a selector, the :not() filter is the easiest way to go about it. Append this filter to your selector along with a selector as its parameter, and the results set will return any elements that match the original selector, but not the selector passed as a parameter to :not().
For example, select a paragraph that does not have class foo:
$("p:not(.foo)");
Selecting Even or Odd Elements
Similar to :first and :last, the :even and :odd filters are syntactically simple and return exactly what you might expect: the even or odd elements from a result set.
Selecting Elements by Index
Note:
An element’s index refers to its position among other elements in the set. Counting in programming starts a zero (0), so the first element is at index 0; the second is at index 1, and so on.
In the event that you need to grab a particular element by its index, the :eq() filter allows you to specify which element is needed by passing an index as the filter’s parameter:
$("p:eq(3)");
Content Filters
Filters are also available to select elements based on their content. These can range from containing certain text to surrounding a given element.
Selecting Elements That Contain Certain Text
To select only elements that contain certain text, use the :contains() filter, where the text to be matched is passed as a parameter to the filter:
$("p:contains(Another)");
Selecting Elements That Contain a Certain Element
If you need to select only elements that contain another element, you would use the :has() filter. This works similarly to :contains(), except it accepts an element name instead of a string of text:
$("p:has(span)");
Selecting Elements That Are Empty
To find elements that are empty (meaning the element contains neither text nor any other elements), the :empty filter comes into play.
In the HTML example you’re using, the only empty elements are not visible. Select them by looking for any empty element:
$(":empty");
Selecting Elements That Are Parents
The opposite of :empty, :parent will only match elements that contain children, which can be either other elements, text, or both.
Select all paragraphs that are parents using the following:
$("p:parent");
Visibility Filters
Visibility filters, :hidden and :visible, will select elements that are, respectively, hidden and visible.
Select all visible paragraphs like so:
$("p:visible");
Child Filters
Child filters add an alternative to the use of :even, :odd, or :eq(). The main difference is that this set of filters starts indexing at 1 instead of 0 (like :eq() does).
Selecting Even or Odd Parameters or Parameters by Index or Equation
One of the more versatile filters, :nth-child() provides four different options to pass as a parameter when selecting elements: even, odd, index, or an equation.
Like other child filters, this one starts indexing at 1 instead of 0, so the first element is at index 1, the second element at 2, and so on.
Using :odd, the result set contained the paragraphs with a class of foo and an ID of foo; select odd paragraphs using :nth-child() to see the difference in how the filters handle by executing the following command:
$("p:nth-child(odd)")
Selecting First or Last Child Elements
While very similar to :first and :last, :first-child and :last-child differ in that the returned element set can contain more than one match. For instance, to find the last span that is a child of a paragraph element, you might use the following:
$("p span:last");
Form Filters
Matching by Form Element Type
The most common form-specific filters simply match form element types. The available filters are :button, :checkbox, :file, :image, :input, :password, :radio, :submit, and :text.
To select all radio inputs, use the following code:
$("input:radio");
Selecting Only Enabled or Disabled Form Elements
Additionally, filters to select enabled or disabled form elements are available using :enabled and :disabled. To select all disabled form elements, use the following code:
$(":disabled");
Selecting Checked or Selected Form Elements
Radio and check box inputs have a checked state, and select inputs have a selected state. Filters are provided to retrieve the form elements that are in either state using :checked or :selected, respectively.
To select the currently checked radio button in your HTML example, execute the following code in the console:
$(":checked");
This returns the radio input that is currently selected.
Example
Find tags with class fontstyle0, and add class test.
<script> $(window).on('load',function() { $(".fontstyle0").addClass("test"); }); </script> <style> .test{ font-size: 120%; color: #ff6600; } </style>