Jquery selecting elements with incomplete names. jQuery selectors and filters. Narrowing the set to elements that have specific children

Save this page to test the examples below.

In most cases, working with jQuery is done in two steps, following the same pattern:

    The first step is to use the $() function to select an initial set of page elements that match a certain selection criterion, which are returned as a jQuery object containing them;

    and the second is to perform one or more operations on each element of the set, leading to the creation of a final set.

In this article we will focus on the first of the stages. We will look at jQuery methods that allow you to manage the selected set and adjust its composition in exact accordance with specific tasks. Usually they start from a certain pre-selected set of elements, influencing which they ensure that only the truly necessary elements remain in it.

Expanding the selection set

The add() method allows you to add to an existing jQuery object additional elements. Various options The calls to this method are given in the table below:

Like many jQuery methods, the add() method returns a jQuery object that can be used to call other methods, including subsequent calls to the add() method. An example of using the add() method to expand a previously found set is given below:

$(function() ( var labelElems = document.getElementsByTagName("label"); var jq = $("img"); $("img:even").add("img").add(jq) .add (labelElems).css("border", "thick double red" ));

This scenario uses three approaches to add elements to the initial set: using another selector, using HTMLElement objects, and using another jQuery object. Having built the right set objects, we call css method(), setting their properties border meanings, ensuring that the inscriptions are surrounded by frames drawn with thick double lines, as shown in the figure:

Narrowing down the set of selected items

There are a number of methods that allow you to remove elements from an existing set. Their short description shown in the table below. Each of these methods returns a new jQuery object containing a stripped-down set of elements. The jQuery object on which the method is called remains unchanged:

Element filtering methods Method Description
eq(index) Excludes all elements from a set except the element at the specified index
filter(condition) Eliminates elements from a set that do not meet a specified condition. Detailed description valid types of arguments are given below
first() Removes all elements from a set except the first one
has(), has(jQuery),
has(HTMLElement),
has(HTMLElement)
Excludes from the set elements that have no children matching the specified selector or jQuery object, or children that do not include specified Objects HTMLElement
last() Eliminates all elements from a set except the last one
not(condition) Excludes from a set all elements that match a specified condition
slice(start, end) Eliminates from a set all elements whose indexes are outside the specified range
Narrowing the set to one element

The simplest methods that can be used to reduce the set of selected elements are the first() , last() , and eq() methods. These three methods allow you to select a specific element based on its position in the set of elements contained in the jQuery object. A corresponding example is given below:

$(function() ( var jq = $("label"); // selecting the first element and influencing it jq.first().css("border", "thick double red"); // selecting the last element and influencing it jq.last().css("border", "thick double green"); // selecting an element with the specified index and influencing it jq.eq(2).css("border", "thick double black"); "); jq.eq(-2).css("border", "thick double black"); ));

Note that the eq() method is called twice. If the argument is positive, index counting starts at the first element in the set contained in the jQuery object. If the argument is negative, the indices are counted in reverse direction, starting from the last element. The result of the script is shown in the figure:

Narrowing a set to elements whose indices belong to a given range

If you want to keep only elements in the selected set whose indices belong to a given range, use the slice() method. A corresponding example is given below:

$(function() ( var jq = $("label"); jq.slice(0, 2).css("border", "thick double black"); jq.slice(4).css("border" , "thick solid red");

The slice() method takes starting and ending index values ​​as arguments. Indexes are counted from zero, and the element to which the final index corresponds is not included in the result set. Therefore, arguments 0 and 2 correspond to the selection of the first two elements.

If the second argument is omitted, then the selection of elements continues until the end of the existing set. Therefore, using the single argument 4 for a set of six elements corresponds to selecting the last two elements (indexed 4 and 5). The result is shown in the figure:

Filtering elements

The filter() method allows you to set a condition. Elements that do not satisfy the specified condition are excluded from the set. Possible options using the filter() method, corresponding in various ways setting conditions are described in the table below:

An example of using all four options for specifying filter() method arguments is given below:

$(function() ( // selection of elements, in value src attribute which // contains the string "astor" $("img").filter("").css("border", "thick double red");

// selecting elements containing the string "daffodil" var jq = $("");

$("label").filter(jq).css("color", "blue"); // selecting elements that are the specified element var elem = document.getElementsByTagName("label");$("label").filter(elem).css("font-size", "1.5em");

The not() method works similarly to the filter() method, but reverses the filtering process. Possible options for calling the not() method are similar to calling the filter() method.

Narrowing the set to elements that have specific children

The has() method can be used to keep in the selection set only those elements that have specific children, specified either by a selector or by one or more HTMLElement objects. An example of using the has() method is given below:

$(function() ( $("div.dcell").has("img").css("border", "thick solid red"); var jq = $(""); $("div.dcell ").has(jq).css("border", "thick solid blue"); ));

In this scenario, members that do not have certain children are excluded from the selected set. In the first case, when a selector is used, elements that do not have any img children whose src attribute is equal to astor are removed from the set. In the second case, using a jQuery object, the same thing happens to elements that do not have any children with a for attribute value containing the letter p. The result of the script is shown in the figure:

Convert a selection set

The map() method provides a flexible way to use one jQuery object to create another. A function is passed as an argument to the map() method. This function is called for each of the elements included in source object jQuery, and the HTMLElement objects it returns are included in the resulting jQuery object.

An example of using the map() method is given below:

$(function() ( $("div.dcell").map(function(index, elem) ( return elem.getElementsByTagName("img"); )).css("border", "thick solid red"); $("div.dcell").map(function(index, elem) ( return $(elem).children(); )).css("border", "thick solid blue" ));

This script performs two conversion operations. The first of them, which uses software interface DOM, returns the first of the img elements occurring in each element of the set. The second operation, which takes advantage of the jQuery object's capabilities, returns the first element of the set contained in the jQuery object, which is returned by the children() method (this method returns the child nodes of each of the elements contained in the jQuery object).

Testing a set of selected elements

To find out whether at least one of the selected elements meets a given condition, you can use the is() method. Possible uses of the is() method are similar to the not() and filter() filtering methods.

If a function is passed as an argument, then jQuery calls that function for each element in the jQuery object, passing it the index of that element as an argument and setting the this variable to point to the element itself. An example of using the is() method is given below:

$(function() ( var isResult = $("img").is(function(index) ( return this.getAttribute("src").indexOf("rose.png") != -1; )); console .log("Result: " + isResult ));

In this script, we check to see if a jQuery object contains an element with a src attribute value that includes the string "rose.png".

Return to previous state modified set of selected elements

jQuery allows you to save the state of the selected set of elements when it changes by calling chaining methods. You can benefit from this circumstance using two methods described in the table below:

The end() method can be used to return the previous selected set, allowing you to select some elements, expand or narrow it, perform some operations, and then return to the original set, as shown in the example below:

$(function() ( $("label").first().css("border", "thick solid blue") .end().css("font-size", "1.5em"); )) ;

In this scenario, we start by selecting all the label elements in the document. Next, we narrow the selection by calling the first() method (to get the first matching element) and then set the value CSS border properties using the css() method.

The end() method is called next to return the previous selection set (resulting in you being given all the label elements again, not just the first one), and then the css() method is called again, this time to set the value of the font-size property. The result of the script is shown in the figure.

jQuery is Javascript library, which makes it easy to work with DOM, events, CSS and AJAX, and allows you to easily create animations. main feature jQuery is cross-browser compatible (yes, and Internet Explorer 6 too :). The jQuery slogan sounds like this: “Write less, do more”, which translated into Russian means “Write less, do more” (or “The slower you go, the further you will go” :). These words perfectly fit the description of this library and are completely justified.

First steps with jQuery

First, you will need to download the library of the same name. You can do this on the official jQuery website. After this, you should connect jQuery to your HTML page. You can do this by adding a script tag to the head of the document:


Connect jQuery


After this you can start using jQuery.

Selectors in jQuery

It's time to talk about selectors. Selectors in jQuery are the same CSS selectors, just modified. They are modified because the jQuery programmers added many useful selectors for convenient search the necessary elements.

Let's look at a code example:

Example 1





Paragraph 1


Paragraph 2


Paragraph 3




// yours will be here javascript code


Examples of obtaining each document element:

$(document.body) - body element
$("div") - selector returns all div elements
$("p") or $("div p") - all paragraphs p (3 pieces)
$("div > p") - returns paragraphs that are immediate child nodes of the div element
$("p:first") - paragraph No. 1
$("#pEl") or $("p#pEl") - will return a paragraph with identifier (id) "pEl"
$("p.second") - will return a paragraph with class "second"
$("p:eq(1)") - will return the paragraph with index 1 (indices start at 0, paragraph No. 2 will be returned)
$("p:last") - returns the last paragraph
$("p.third#third") - will return paragraph No. 3

Notice how easy it is to find the element we need. Forget about document.getElementById("id") and document.getElementsByTagName("p"), we won't need them anymore.

Example 2

Let's take a look at some of the more powerful features of jQuery. To do this, let's draw a table

Header 1 Header 2
Cell 1Cell 2
Cell 3Cell 4
Cell 5Cell 6
Cell 7Cell 8
Press me

In this example I used the ":odd" selector, which selects everything not even elements and applied it to the table rows (tr tags). ":even" in turn selects even ones (0, 2, 4, ...).
And so we need to select all the odd rows of the table, but we don’t want the first row, which is the header (th elements), to change its color and the stripes to start from the third row. In this case, the selector ":not(selector)" will be useful to us. It is used like this:

$("table tr:not(:first):odd") - select all even tr elements except the first

Here is the source javascript:

$("button").toggle(function() (
$("table tr:not(:first):odd").css("background", "#eee");
// 1st click, set the background to gray
),function() (
$("table tr:not(:first)").css("background", "none");
// 2nd press, remove the background from all tr
});

Example 3 - working with forms

On the jQuery website, in the selectors section, there is a separate subsection dedicated to working with forms. Selectors provide convenient work with checkboxes, buttons, input fields, and so on. Let's draw the shape.

In this lesson, we'll learn about form element selectors, which we'll use as an argument to the jQuery("selector") function to select elements.

Purpose of form element selectors

Form element selectors are designed to select elements depending on:

  • their types (type attribute values) are :button, :checkbox, :file, :image, :password, :radio, :reset, :submit, :text.
  • whether their tag is input , textarea , select or button - :input .
  • whether the element has focus or not - :focus .
  • whether elements are in an active state (:enabled) or inactive state (:disabled).
  • whether option elements are in the selected state or not - :selected .
  • whether the checkbox , select and radio elements are in the selected state or not - :checked .
Form element selectors

    :button - selects all button elements and elements with type="button" . The $(":button") selector is equivalent to $("button, input") .

    The:button selector is not part of the CSS specification, it is implemented exclusively in jQuery. So when you use it in a selector to filter elements, you won't get the performance gain that the native DOM querySelectorAll() method provides. To improve query performance in modern browsers, use the following construction: $("selector").filter(":button");

    For example, select all button elements or elements with type="button" that are located inside the form:

    Update data $("form:button");

    //or using the filter method $("form *").filter(":button");

    :checkbox - selects all elements with type="checkbox" . The $(":checkbox") selector is equivalent to $("") .

    The:checkbox selector is not part of the CSS specification, it is implemented exclusively in jQuery. So when you use it in a selector to filter elements, you won't get the performance gain that the native DOM querySelectorAll() method provides. To improve query performance in modern browsers, use the following construction: $("input");

    For example, select all input elements that have the type="checkbox" attribute, i.e. are checkboxes:

    $("input:checkbox");

    //or using the attribute selector $("input");

    :checked - selects all elements with a checked or selected state. The:checked selector is for checkbox , select elements, and radio buttons.

    Linux Windows Chrome Firefox Value 1 Value 2 Value 3

    :disabled - selects all elements that are disabled.

    Before the :disabled selector, as well as before pseudo-class selectors (i.e. those that begin with " : "), it is recommended to specify a tag or another selector (for example, the name of the class). If you do not specify anything before the " : " sign, then the use of a universal selector (" * ") is implied. In other words, $(":disabled") is equivalent to $("*:disabled") . But in this case, it is more correct to use the input tag instead of " * ": $("input:disabled") .

    The:disabled selector is different from the attribute selector. The:disabled selector tests for the Boolean value (true/false) of the element's disabled property, while the attribute selector simply tests for whether the element has a disabled attribute.

    The:disabled selector can only be used to select HTML elements that support the disabled attribute: , , , , and .

    $("input:disabled");

    :enabled - selects all elements that are enabled.

    Before the :enabled selector, as well as before pseudo-class selectors (i.e. those that begin with " : "), it is recommended to specify a tag or another selector (for example, the name of the class). If you do not specify anything before the " : " sign, then the use of a universal selector (" * ") is implied. In other words, $(":enabled") is equivalent to $("*:enabled") . But it is more correct in this case to use the input tag instead of " * ": $("input:enabled") .

    The:enabled selector can only be used to select HTML elements that support the disabled attribute: , , , , , and .

    $("input:enabled");

    :file - selects all elements with type="file" . The:file selector is equivalent to .

    Before the:file selector, as well as before pseudo-class selectors (i.e. those that begin with " : "), it is recommended to specify a tag or another selector (for example, the name of the class). If you do not specify anything before the " : " sign, then the use of a universal selector (" * ") is implied. In other words, $(":file") is equivalent to $("*:file") . But it is more correct in such cases to use the input tag instead of " * ": $("input:file") .

    The:file selector is not part of the CSS specification, it is implemented exclusively in jQuery. So when you use it in a selector to filter elements, you won't get the performance gain that is provided by the native DOM querySelectorAll() method. To improve query performance in modern browsers, use the attribute selector.

    $("input:file");

    // $("input");

    :focus - selects the element that has focus. Before the:focus selector, as well as before pseudo-class selectors (i.e. those that begin with " : "), it is recommended to specify a tag or another selector (for example, the name of the class). If you do not specify anything before the " : " sign, then the use of a universal selector (" * ") is implied. In other words, $(":focus") is equivalent to $("*:focus") . If you need to get the current element that has focus, then use the following code: $(document.activeElement) . This method

    gets an element without searching for it in the DOM tree.

    :image - selects all elements with type="image" . The:image selector is equivalent to .

    The:image selector is not part of the CSS specification, it is implemented exclusively in jQuery. So when you use it in a selector to filter elements, you won't get the performance gain that is provided by the native DOM querySelectorAll() method. To improve query performance in modern browsers, use .

    $("input:image");

    The:input selector is not part of the CSS specification, it is implemented exclusively in jQuery. So when you use it in a selector to filter elements, you won't get the performance gain that is provided by the native DOM querySelectorAll() method. To improve query performance in modern browsers, use the following construction: $("selector").filter(":input");

    Parameter 1 Parameter 2 $("*:input");

    // $("form *).filter(":input");

    :password - selects all elements with type="password" . The selector:password" is equivalent to .

    Before the:password selector, as well as before pseudo-class selectors (i.e. those that begin with " : "), it is recommended to specify a tag or another selector (for example, a class name). If you do not specify anything before the " : " sign, then the use of a universal selector (" * ") is implied. In other words, $(":password") is equivalent to $("*:password") . But it is more correct in such cases to use the input tag instead of " * ": $("input:password") .

    The:password selector is not part of the CSS specification. It is implemented exclusively in jQuery. So when you use it in a selector to filter elements, you won't get the performance gain that is provided by the native DOM querySelectorAll() method. To improve query performance in modern browsers, use .

    $("*:password");

    // $("");

    :radio - selects all elements with type="radio" . Selector:radio is equivalent to .

    Before the:radio selector, as well as before pseudo-class selectors (i.e. those that begin with " : "), it is recommended to specify a tag or another selector (for example, the name of the class). If you do not specify anything before the " : " sign, then the use of a universal selector (" * ") is implied. In other words, $(":radio") is equivalent to $("*:radio") . But it is more correct in this case to use the input tag instead of " * ": $("input:radio") .

    The:radio selector is not part of the CSS specification, it is implemented exclusively in jQuery. So when you use it in a selector to filter elements, you won't get the performance gain that is provided by the native DOM querySelectorAll() method. To improve query performance in modern browsers, use .

    The:reset selector is not part of the CSS specification, it is implemented exclusively in jQuery. So when you use it in a selector to filter elements, you won't get the performance gain that is provided by the native DOM querySelectorAll() method. To improve query performance in modern browsers, use .

    $(":reset");

    // $("");

    :selected - selects all elements that are in the selected state. The:selected selector only works on option elements and does not work on checkbox and radio elements. To work with the latter, use the selector:checked .

    The:selected selector is not part of the CSS specification, it is implemented exclusively in jQuery. So when you use it in a selector to filter elements, you won't get the performance gain that is provided by the native DOM querySelectorAll() method. To improve query performance in modern browsers, use the following construction: $("selector").filter(":selected");

    Flowers Shrubs Trees Earth Grass $(":selected"); // $("*").filter(":selected");:submit - selects all elements with type="submit" . The selector:submit is for

    button elements

    or input .

    The:submit selector is not part of the CSS specification, it is implemented exclusively in jQuery. So when you use it in a selector to filter elements, you won't get the performance gain that is provided by the native DOM querySelectorAll() method. To improve query performance in modern browsers, use input, button

    $(":submit");

    // $("input,button"); :text - selects all elements with type="text" . The jQuery $(":text") function allows us to select elements. Before the:text selector, as well as before pseudo-class selectors (i.e. those that begin with " : "), it is recommended to specify a tag or another selector (for example, the name of the class). If you do not specify anything before the " : " sign, then the use of a universal selector (" * ") is implied. In other words, $(":text") is equivalent to $("*:text") . But it is more correct in this case to use the input tag instead of " * ": $("input:text") .

    Beginning with

    jQuery versions

    The:text selector is not part of the CSS specification, it is implemented exclusively in jQuery. So when you use it in a selector to filter elements, you won't get the performance gain that is provided by the native DOM querySelectorAll() method. To improve query performance in modern browsers, use .

    $(":text");

// $("input"); JQuery selectors are one of the most important parts.

jQuery libraries

jQuery selectors

JQuery selectors allow you to select and manipulate HTML element(s). JQuery selectors are used for "find" (or select) HTML elements , based on their name, ID, classes, types, attributes, attribute values ​​and more. It is based on existing CSS selectors

, and in addition, it has some selectors of its own.

All selectors in JQuery begin with a dollar sign and a parenthesis: $().

Selection element Selector jquery element

selects elements based on the element name.

You can select all elements

On a page like this:

example

When the user clicks on the button, everything

Elements will be hidden:

#id Selector

JQuery's #id selector uses the ID attribute of an HTML tag to find a specific element.

The ID must be unique within the page, so you should use the #ID selector if you want to find a single, unique element.

On a page like this:

To find an element with a specific ID, write a hash character followed by the HTML element ID:

When the user clicks on the button, the element with id="test" will be hidden:

Selection element .class Selector Jquery class

finds elements with a specific class.

On a page like this:

To find elements with a specific class, write the character period followed by the class name:

When the user clicks on the button, elements with class="test" will be hidden: More examples of JQuery selectorsSelects all evenSelects all even
$("*") Syntax Description Example Selects all elements
Try it $(this) Selects all elements
Selects the current HTML element $("p.intro")

Selects all

Selects all elements
Elements with class="intro" $("p:first")

Selects the first

Selects all elements
Element $("p:first")
  • $("ul li:first")
  • Selects all elements
    element of the first $("p:first")
  • $("ul li:first-child")
  • Selects all elements
    $("") element of every Selects all elements
    Selects all elements with an href attribute $("p.intro") $("a") Selects all elements
    Selects all elements with an href attribute $("p.intro") elements with a target attribute value equal to "_blank" Selects all elements
    elements with a target attribute value NOT equal to "_blank" $(":button") Selects all elements
    Selects all elements and elements of type="button" $("tr:even")
    Selects all elements
    elements $("tr:odd")
    Selects all elements
    Selects all odd

    If your site contains many pages and you want your Jquery functions to be easy to maintain, you can put your jQuery functions into a separate .js file.