Using fast selectors for jQuery. How jQuery parses a selector

In order for the script to work with some element of the page, this element must first be found. There are several ways to do this in JavaScript. The found element is usually assigned to a variable, and later, through this variable, srkipt refers to the element and performs some actions with it.

Search by id

If the id attribute is set for an element in the page code, then the element can be found by id. This is the easiest way. The element is searched for using the getElementById () method of the global document object.

document.getElementById (id)

Parameters:

id - the id of the element to find. id is a string, so it must be quoted.

Let's create a page, add an element to it and assign an id to it, and find this element in the script:

HTML code:

JavaScript:

var block \u003d document.getElementById ("block"); console.log (block);

We assigned the found element to the variable block and printed the variable to the console. Open your browser console, it should have an item listed.

Since searching by id is the easiest and most convenient way, it is often used. If you need to work with some element in the script, then the id attribute is set for this element in the page code, even if it was not set earlier. And they find the element by id.

Search by class

The getElementsByClassName () method allows you to find all the elements belonging to a specific class.

document.getElementsByClassName (class)

Parameters:

class - the class of elements to find

The method returns a pseudo-array containing the elements found. It's called a pseudo-array because many of the array methods don't work for it. But the main property remains - you can refer to any element of the array. Even if only one element is found, it is still in the array.

Let's add elements to the page and give them a class. We will place some of the elements inside the block that we created earlier. Let's create the other part outside the block. The meaning of this will be clear a little later. The page will now look like this:

HTML code:

JavaScript:

Now only those elements are found that are located in the block.

Search by tag

The getElementsByTagName () method finds all elements with a specific tag. It also returns a pseudo-array with the elements found.

document.getElementsByTagName (tag)

Parameters:

tag - the tag of the elements to find

Let's find all p tags that are on the page:

var p \u003d document.getElementsByTagName ("p"); console.log (p);

This method can also be applied not to the entire document, but to a specific element. Find all p tags in the block.

Search by selector

There are querySelector () and querySelectorAll () methods that find elements that match a specific selector. That is, elements will be found to which the style would have been applied if it had been specified for such a selector. At the same time, the presence of such a selector in the page style is not at all necessary. These methods have nothing to do with CSS. The querySelectorAll () method finds all elements that match the selector. And the querySelector () method finds one element that is the first in the page code. These methods can replace all the ways to find elements discussed earlier, because there is an id selector, a tag selector, and many others.

document.querySelector (selector)

document.querySelectorAll (selector)

Selectors are written in the same way as in CSS, just remember to put quotes.

Let's add a list to the page and find it by the selector. We are looking for only one element and we know for sure that it will be the first, because there is only one on the page. Therefore, in this case, it is more convenient to use the querySelector () method. But when using this method, you need to take into account that the same elements can be added to the page in the future. However, this applies to most methods.

HTML code:

These methods can also search for elements not in the entire document, but inside a concrete element.

In the example, we only used selectors by tag. Try to find page elements using other selectors.

Neighboring elements

For the found element, you can find neighbors. Each element is an object, and neighboring elements can be obtained through the properties of this object. The previousElementSibling property contains the previous element, and the nextElementSibling property contains the next element.

element.previousElementSibling

element.nextElementSibling

Find the element following the block:

Child elements

The children property contains an array of children.

element.children

Let's find the children of the block.

Document Object Model - DOM is nothing more than a tree structure consisting of tags that exist in Html document.

We have all these elements Htmllocated next to each other that we want to receive, and then read the data in them or change. There are many ways to find these tags as they are arranged in a tree structure. In this article, you will learn how to use two built-in functions JavaScript, such as the querySelector and querySelectorAll for searching html tags.

QuerySelector method

To understand the essence of the functioning of the methods querySelector and querySelectorAll look at the following HTML:















In this example, we have one div with id main and four nested elements div and img, each of which has a class value pic-container and profileImage respectively. In the next few sections, we will apply the functions querySelector and querySelectorAll On this HTML code and see what happens.

querySelector

Function querySelector works like this:

Var element \u003d document.querySelector ("< CSS selector >");

QuerySelector function takes an argument and this argument is CSS selector for the element you want to find. What returns querySelector function, is the first element it finds, even if there are other elements that may be similar to this selector.

Looking at Html from our previous example, if we want to access divwhose id is main, you need to write the following:

Var element \u003d document.querySelector ("# main");

Insofar as main is an identifier, the selector syntax to get it would be #main ... Likewise, the class selector pic-container :

Var element \u003d document.querySelector (". Pic-container");

The first block is returned div whose class value is pic-container ... Remaining elements div with class value pic-container are simply ignored.

The selector syntax for this function was not specially created, so you can use the exact syntax you would use for selectors in a stylesheet!

That's all, and in the next article I will tell you about the following function querySelectorAll.

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

Var primaryHeadings \u003d document.getElementsByTagName ("h1");

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

Var ou812 \u003d document.getElementById ("eddie");

This code selects the element with id \u003d “eddie”.

Var guitars \u003d document.getElementsByClassName ("axes");

We can also select elements by their class names.

Add some Sizzle

Various JavaScript frameworks provide their own selector composing capabilities. One of the most successful was Sizzle, which later morphed into jQuery. Unlike its descendant, Sizzle could only work with and manipulate the DOM. If you don't need all the rest of jQuery's functionality, you can still download Sizzle as a standalone library today.

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

$ ("# dave"). css ()

This code extracts the html element with id \u003d "dave" and allows you to work with its css styles.

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

The 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 the official part of the HTML5 specification and can be used to write XHTML pages. The new syntax is very simple:

Document.querySelector ("# eddie")

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

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

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

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

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

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

Several very important points

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

Not all browsers support the 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 composed 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 are on the page at a given time. This means that if you make any dynamic changes to the code (adding or removing elements via JavaScript), you will need to reuse the querySelectorAll method.

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

In this lesson, we will look at the methods of the document object, which are designed to search for a node or collection of nodes throughout a document. And also methods of the node object (node), which perform similar actions, but already among their child nodes.

Methods for finding a node or collection of nodes in a tree

In the previous lesson, we looked at the properties with which we can navigate the tree and find the nodes we need. However, finding nodes using their properties is very difficult and ineffective. Therefore, to find nodes in a tree, web developers typically use dedicated methods on the document object or node.

GetElementById () method

The getElementById (elementID) method returns the element in the document with the specified identifier (id \u003d "elementID") as a Node object. If the element with the specified identifier does not exist, then this method returns null.

According to the standard, you cannot have several elements in a document with the same id attribute value, i.e. the identifier value must be unique within the same document. Nevertheless, if you have several elements with the specified id in your document, then the getElementById () method will return the first element found.

document.getElementById (elementID)

This method has one required parameter (elementID), which is a string containing the value of the id attribute of the element you want to retrieve.

For example, change the color of the text of an element with id \u003d "nameArticie".

Article title

  • 1 point
  • 2 point
  • 3 point

GetElementsByClassName () method

The getElementsByClassName (className) method returns all found elements in the document (for document) or among child nodes (for node) that have the specified class name (class \u003d "className") as a NodeList object (collection of nodes). In other words, this method returns a NodeList object, which is a collection of elements (nodes) with the class name specified in the parameter of this method.

To get the number of found nodes you need to use the length property of the NodeList object. And in order to iterate over all the nodes in the collection, you can use the following loop:

Var elementsList \u003d document.getElementsByClassName ("list"); for (var i \u003d 0; i

document.getElementByClassName (className);
node (node) .getElementByClassName (className);

This method has one required parameter (className), which is a string containing the name of the class of elements that you want to receive. If you want to get elements that have several specified classes, then they must be separated in the parameter of this method using a space. For example, get a collection of nodes that have classes classl and class2:

Document.getElementsByClassName ("classl class2");

For example, change the background color of elements that have a list class:

Article title

  • 1 point
  • 2 point
  • 3 point
  • 1 point
  • 2 point

For example, get a collection of elements (nodes) that have the list class. Next, get 2 nodes in this collection, i.e. node with index 1. Then change the background color of the resulting node.

// Get a collection of elements that have the list class var elementsList \u003d document.getElementsByClassName ("list"); // Get the 2nd node in the collection var secondList \u003d elementsList; // Change the background color of the element secondList.style.backgroundColor \u003d "red";

GetElementsByTagName () method

The getElementsByTagName (tagname) method returns all found elements in the document (for document) or among child nodes (for node) that have the specified tag as a NodeList object (collection of nodes). Getting a specific node in a collection is done by index. The counting of elements (nodes) in the collection starts from 0.

document.getElementsByTagName (tagname);
node (node) .getElementsByTagName (tagname);

This method has one required parameter (tagname), which is a string containing the tag name in uppercase letters. If you specify a string containing an asterisk ("*") as a parameter, then we get all the elements in the document (for the document object) or all the child elements of the node (for the node object).

To get the number of found nodes contained in the collection, you must use the length property of the NodeList object. And in order to iterate over all the nodes in the collection, you can use the following loop:

Var elementsList \u003d document.getElementsByTagName ("LI"); for (var i \u003d 0; i

For example, change the background color of LI elements:

Article title

  • 1 point
  • 2 point
  • 3 point

For example, get a collection of UL items. Then get 1 node in this collection, i.e. the node with index 0. Then get the collection of LI child nodes for this node. Finally, change the font size of each item in this collection.

// Get the collection of UL elements var elementsUL \u003d document.getElementsByTagName ("UL"); // Get 1 node in this collection var elementUL \u003d elementsUL; // Get the collection of LI Children of the elementUL node var elementsLI \u003d elementUL.getElementsByTagName ("LI"); // iterate over all the elements in the collection for (var i \u003d 0; i

GetElementsByName () method

The getElementsByName (name) method returns all found elements in the document that have the specified name (value of the name attribute) as a NodeList object (collection of nodes).

Items (nodes) are added to the collection in the order in which they appear in the tree. Getting a specific node in a collection is done by index. The counting of elements (nodes) in the collection starts from 0.

Var elementsList \u003d document.getElementsByName ("phone"); for (var i \u003d 0; i

Note: HTML5 has deprecated the name attribute and has replaced it with the id attribute for most elements.

document.getElementsByName (name)


This method has one required parameter (name), which is a string containing the value of the name attribute.

For example, change the background color of elements that have a name attribute with the value phone (name \u003d "phone"):

Phone: Another phone:

QuerySelector () method

The querySelector () method returns the first element found in the document (for document) or among child nodes (for node) that matches the CSS selector specified as a parameter to this method. If no element matches the CSS selector, then this method returns null.

document.querySelector (cssSelector)
node.querySelector (cssSelector)

This method has one required parameter (cssSelector), which is a string containing a CSS selector according to which the element is selected.

For example, change the text color of the first found element that matches the #main p selector:

...

...

For example, get a collection of DIV elements in a document. Then get 1 node in this collection, i.e. node with index 0. For this node, find among its child nodes the first element that matches the CSS selector h1 + p. Then change the font size of this element.

// Get a collection of DIV elements var elementsDIV \u003d document.getElementsByTagName ("DIV"); // Get 1 node in this collection var elementDIV \u003d elementsDIV; // Get the p node immediately after the h1 node // Search for the node among the child nodes of the node, which is stored in the elementDIV variable var elementP \u003d elementDIV.querySelector ("h1 + p"); // change the font size of the element elementP.style.fontSize \u003d "30px";

QuerySelectorAll () method

The querySelectorAll () method returns all found elements in the document (for document) or among child nodes (for node) that match the CSS selector specified as a parameter to this method, as a NodeList object (collection of nodes). The nodes in the collection are referenced by index. The counting of elements (nodes) in the collection starts from 0.

To get the number of found nodes, use the length property of the NodeList object. And in order to iterate over all the nodes in the collection, you can use the following loop:

Var elementsList \u003d document.querySelectorAll ("# main p"); for (var i \u003d 0; i

document.querySelectorAll (cssSelector);
node (node) .querySelectorAll (cssSelector);

This method has one required parameter (cssSelector), which is a string containing a CSS selector according to which elements are selected. To specify several selectors in a parameter of this method, they must be separated by commas.

For example, change the text color of elements matching the #main p selector:

...

...

For example, get a child node that has an id attribute of sidebar. Change the background color of the p children of the node obtained in the previous step:

// get the element (node) with id \u003d "sidebar" var sidebar \u003d document.getElementById ("sidebar"); // get the collection of nodes that match the "p" selector var elementsListP \u003d sidebar.querySelectorAll ("p"); // iterate over all the elements in the collection for (var i \u003d 0; i

The task

Write JavaScript code using the getElementById (), getElementsByClassName (), getElementsByTagName (), querySelector (), querySelectorAll () methods for the following tasks:

  1. Get all p elements located in the main block;
  2. Get the aside block located in the container div;
  3. Get the footer block located in the body container.

Perform each task in as many different ways as possible.

The task that very often confronts beginner javascript developers is the selection of an element on a web page by its id attribute.

Let's assume we have some code on the page.

Block content.

How can you select an element with id \u003d "elem" and perform a number of actions with it?

There are several options for solving the problem. Let's look at them now.

Option 1. Use the Javascript getElementById method.

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

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

Block content.

Note that these lines of code (script) are below the element itself. This is a prerequisite for the operation of this script, because Javascript code is executed as the page loads. If we place the code above, then we will refer to an element on the page that has not yet been loaded, i.e. it will not be in the code at the time of the script execution yet. There are ways to avoid this, but that 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 you can solve this problem in another way.

Option 2. Using the Jquery library.

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.

In order to refer to an element by its id, you need to use the 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 be connected first.

It is added in the section , one way to do this is to add the following line of code:

There must be an Internet connection for the library to load.

Block content.

The script itself, as in the previous example, must be located below the code of the element with which you want to interact.

Thus, we have analyzed two ways of how you can select an element on a web page by its id attribute and interact with it. Choose the method that suits you and use it in practice.