Jquery selectors examples. JQuery selectors. Functions in a separate file

jQuery is a Javascript library that makes it easy to work with the DOM, events, CSS and AJAX, and makes it easy to 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 “If you drive more quietly, you will continue” :). 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, only 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




// your javascript code will go here


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 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 previous lessons we discussed the question general concepts jQuery and how to connect it.
This article will focus on using selectors in jQuery (CSS and XPath), which allow you to select one or more DOM elements with ease and precision. Each selector will have a code and an example of its application. Using jQuery selectors does not cause problems working in old browsers, for example IE 6, as it contains mechanisms CSS work 1-3.

jQuery code structure Dollar sign $ - denotes usage jQuery, selector - DOM element with whom we work and special function jQuery with its parameters (for example, animation, deployment, movement, etc.).

jQuery code example

$(selector).function(parameters);

Selectors in jQuery this lesson We will dwell in detail on the issue of selectors. What is it?

Selector(from the English select - choose) - these are DOM elements ( object model document, such as tags or specially marked blocks) to which we make a request. This concept exists in JavaScript, CSS, and other languages ​​where you need to select a specific element and work with its properties.

Identifiers (id).

If you want to work with a specific element, and just one time(in theory, since in practice some browsers will not disdain reuse identifier), then we assign it a unique id.

HTML code

#id- selects the only element with the passed identifier (id). IN in this case special

jQuery code


$("#special").css("border", "1px solid black");

In the future I will write without tags, I hope it is clear that JavaScript should be enclosed in them. In the example, we select the element with id special, in this case it is a div. In it we use css function and create a black continuous (solid) border (border) of 1 pixel.

Classes.

.class- select all elements with the specified class. That's right, there may be several of them. The main thing is that the class name is the same.

HTML code

First block
Second block
As you can see, there are two elements (div) and they have the same classes.

jQuery code

$(".spec_class").css("border", "1px solid red");
For all elements where spec_class class value the same borders are also created as in the previous example, but red.

Elements.

All elements of a certain type are selected. It's either body, or all divs, or all table and so on.

jQuery code

$("div").css("border", "1px solid green");
U all divs A green frame will appear.

* (all elements) - select absolutely all elements. Even head And body.

jQuery code

$("*").css("border", "1px solid blue");
All elements in your document will have a blue border.

$("*", document.body).css("border", "2px solid black");
Select all the elements in the body and give them a 2 pixel black border.

By type: selector1, selector2, ..., selectorN - we list all elements. Below is an interesting example sharing selectors.

jQuery code

$("div, span, p.spec_class").css("border", "1px solid red");
Selects all div, span and p elements that have spec_class specified. All selectors are simply specified separated by commas.

Hierarchical selectors in jQueryancestor descendant

Selected main element (parent element) and the elements included in it (descendants). Let's look at the example below of the parent form and descendants select.

jQuery code

$("form select").css("border", "1px dashed black");
All select elements and form descendants will have a black dotted border.

parent-child

Now let's select all the children of the parent element.

jQuery code

$("#id > *").css("border", "1px double black");
First, we select all the heirs of the element with id, and then create a double black border with it.

prev and next (previous and next)

We indicate the elements that come next (next) after the element designated as previous (prev).

jQuery code

$("label + input").css("color", "blue").val("Done!");
Select the input elements following the label. We install them CSS properties- the color is in the form of black and the value (.val) is set Ready!

prev ~ siblings

Now we work with sister elements. Find all sisters following the previous element (prev).

jQuery code

$("#prev ~ div").css("border", "3px groove blue");
We are looking for all div elements that are siblings of each other and immediately follow the element with ID #prev. Please note that the example will not select span elements, since the selection is only for div elements.

Basic filters:first

The first element with the specified selector will be selected.

jQuery code

$("tr:first").css("font-style", "bold");
In the first row (tr) in the table, the text will be highlighted in bold.

Now we will select the last element with the specified selector.

jQuery code

$("tr:last").css((backgroundColor: "yellow",fontWeight: "bolder"));
Find the last line (tr) in the table and paint the background in yellow and also install bold font(bolder).

:not(selector)

Using negation filters out elements. Select all inputs that do not have a checkbox, as well as the spans following them

jQuery code

$("input:not(:checked) + span").css("background-color", "yellow");
The meaning of the checkboxes does not change.

Attention! Interesting example , which every second person uses in his practice. How to choose even or odd elements? Then you need to make the lines in the text or even the code readable. Start value 0.

jQuery code

$("tr:even").css("background-color", "#с1с1с1");
Select even rows in the table. The first, third, etc. lines will be highlighted. Attention! The counting is based on indices, and in them the first row has the value 0. Next, rows with indices 0, 2, 4, etc. are selected).

Now we select the odd elements. The index value is calculated starting from 0. Values ​​1,3,5,7, etc. will be selected accordingly. This corresponds to lines 2,4,6, etc., since they are counted in fact, from the first.

jQuery code

$("tr:odd").css("background-color", "#с1с1с1");
The background of odd-numbered lines is colored gray.

:eq(index)

Select a specific element index. In the example, we will color only one row of the table.

jQuery code

$("td:eq(2)").css("color", "blue");
We select element 2 by index. Let me remind you that this will be the 3rd line, since it will be the third index (0,1,2).

:gt(index)

Now we select index values ​​that are greater than those specified in the selector.

jQuery code

$("td:gt(4)").css("text-decoration", "line-through");
We select rows in the table whose element index is greater than 4, that is, their index is 5.6, etc. This corresponds to 6, 7, etc. occurring elements, in our case table rows.

:lt(index)

Now we select index values ​​that are less than those specified in the selector.

jQuery code

$("td:lt(3)").css("color", "red");
All td elements with index m are selected. For example, we are looking for all TD elements with an index less than 3. Since the counting, I remind you once again, is from scratch, these are table rows (td) 1,2,3.

All elements that are headings (h1,h2,h3, etc.) will be selected

jQuery code

$(":header").css(( background:"#c1c1c1", color:"#0085cc" ));
For all headers (h elements) we will set blue font and light gray background.

:animated

All elements that are currently animated will be selected.

HTML code

Make the first div red
jQuery code

$("#run").click(function())(
$("div:animated").toggleClass("colored");
});
function animateIt() (
$("#mover").slideToggle("slow", animateIt);
}
animateIt();
Here the example is a little more complicated. After clicking on the button, we change the color of the animated element (div). There are no changes to non-animated elements.

Let's look at a simple example of how selectors work in jQuery. The file is completely ready for use; you just need to copy the entire code into the created html file. The library in the example is connected with Google servers, therefore for correct operation The file will require an internet connection. Below the code there is a demo version for viewing.



jQuery

#polosa1( position: relative; background: white; width: 200px; height: 50px; border-top: solid 1px #000; )
#polosa2( position: relative; background:blue; width: 200px; height: 50px; )
#polosa3( position: relative; background: red; width: 200px; height: 50px; border-bottom: solid 1px #000; )


function addFlag1())(
$("div:eq(0)").css("background", "white");
$("div:eq(1)").css("background", "green");
$("div:eq(2)").css("background", "red");
}
function addFlag2())(
$("#polosa1, #polosa3").css("background", "red");
$("#polosa2").css("background", "white");
}
function addFlag3())(
$("div").css("background", "red");
}

An example of jQuery selectors working



Flag of Bulgaria
Flag of Austria
USSR flag



Demonstration Download sources
Thank you for your attention! Good luck in your endeavors!


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 is provided by the native DOM querySelectorAll() method. 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 $("") .

    Before the:checkbox selector, as well as before pseudo-class selectors (i.e. those that begin with the ":") sign, 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, $(":checkbox") is equivalent to $("*:checkbox") . But it is more correct in this case to use the input tag instead of *: $("input:checkbox") .

    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 is provided by the native DOM querySelectorAll() method. 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.

    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 is different from:not() . The:enabled selector selects elements that have the disabled boolean property set to false . While :not() selects elements that do not have the disabled attribute set.

    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");

    // $("input");

    :input - Selects all input , textarea , select and button elements in the document. Those. it selects all the form controls.

    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");

    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 .

    $(":radio");

    // $("");

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

    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 .

    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

    1.5.2, the:input selector also selects input elements that do not have a type attribute specified (in which case the element is assumed to have type="text").

    Let's demonstrate the difference between $(":text") and $("") with the following example:

    $("").is(""); // false $("").is(":text"); // true

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");

A task that very often confronts beginners

javascript developers

How can you select an element with id="elem" and perform a series of actions with it?

There are several options to solve the problem. Let's look at them now.

Option 1. Use Javascript method getElementById.

There is a way to access an element by its id using “pure” javascript code, without using any third-party libraries. This method is to use the ggetElementById(“element_id”) method. Thus, we access the element we need by its id.

Let's see how this works with a simple example.

Block content.

alert(document.getElementById("elem").innerHTML); Please note that these lines of code (script) are located below the element itself. This required condition the work of this script, because Javascript code

executed as the page loads. If we place the code above, we will access an element on the page that has not yet loaded, i.e. it will not yet be in the code at the time the script is executed. There are ways to avoid this, but it is beyond the scope of this article.

As a result, if everything works correctly, we will get a pop-up window. This window will display the text that is inside the div block.

Let's now see how we can solve this problem in another way. Option 2. Using.

Jquery libraries

The second option for selecting an element by its id is to use the Jquery library. In practice, in modern scripts, this method is most often used. It is much more convenient and easier to remember.

To refer to an element by its id, you need to use the following construction:

$("#elem")

Here elem is the name contained in the id attribute.

Because We will use a third-party Javascript library called Jquery, then this library must first be included. It is added in the section, one of the ways this can be done is to add next line

code:

In order for the library to be loaded, there must be an Internet connection.

Block content.

alert($("#elem").html());

JavaScript, like CSS, has functionality that allows you to access HTML elements to transform page content. In CSS, this is achieved by writing selectors. There are several ways to organize this functionality in JavaScript, and here is one of them:

Var primaryHeadings = document.getElementsByTagName("h1");

This code extracts all h1 headers and, roughly speaking, places them in the primaryHeadings variable. If there are several headings on the page, then they will all be placed in an array.

Var ou812 = document.getElementById("eddie");

This code selects the element with id = “eddie”.

Var guitars = document.getElementsByClassName("axes");

We can also select elements by the name of their classes.

Let's add some Sizzle

Various JavaScript frameworks provide their own options for creating selectors. One of the most successful was Sizzle, which later became jQuery. Unlike its descendant, Sizzle could only work with and manipulate the DOM. If you don't need all the other jQuery functionality, you can still download Sizzle as a separate library.

With the development of these libraries, the writing of selectors has been significantly reduced and transformed:

$("#dave").css()

This code extracts html element with id=”dave” and allows you to work with its css styles.

Sizzle is not the only one JavaScript library for manipulation html code. There are also other options, for example rangy. However, in my opinion, all of the above is outdated before what awaits you further in this article.

Next level of JavaScript

Many developers started using jQuery so often that they didn’t even notice the dramatic changes in JavaScript itself.

The “JavaScript Selector API” is an official part of the HTML5 specification and can also be used when writing XHTML pages. New syntax very simple:

Document.querySelector("#eddie")

This code is absolutely equivalent to document.getElementById("eddie"). Not impressive? What about this:

Document.querySelector("#eddie h1 + p")

The new functionality allows you to manipulate the DOM using complex CSS expressions.

The querySelector method retrieves only the first element it encounters. To retrieve all, you need to use querySelectorAll:

Var hiFrets = document.querySelectorAll("table#frets tr:nth-child(3)")

This code retrieves every third row from the table with id="frets".

A few very important points

There are several limitations that you should be aware of if you use the querySelector / All method:

Not all browsers support new functionality. If it is important for you that the code works on IE6-7, then it is better to use libraries that can manipulate the DOM: Sizzle or jQuery.

Selectors must be written very carefully, otherwise browsers will not understand them, and the above methods will return null. In general, be very careful, especially when using CSS3 selectors.

Unlike getElementsByTagName, the querySelectorAll method returns a static list of retrieved elements as they appear on the page in this moment time. This means that when you make any dynamic changes into the code (adding, removing elements via JavaScript), you will need to use the querySelectorAll method again.

Try new functionality to get rid of the need to download various kinds of libraries.