the Internet Windows Android

JavaScript - DOM: Methods for searching for nodes. Methods designed to search for a node or collection of nodes in the tree

In this lesson, we consider the methods of the Document object, which are designed to search for a node or collection of nodes throughout the document. As well as the methods of the Node object (node) that perform similar actions, but already among their subsidiaries.

Methods designed to search for a node or collection of nodes in the tree

In the previous lesson, we reviewed the properties with which we can move around the tree and find the nodes we need. But, the search for nodes with their properties the occupation is very difficult and not effective. Therefore, to find knots in a tree, web developers typically use specially designed methods of the Document or node object (NODE).

GetElementByid ()

The GeTelementByid method (ElementID) returns an item in a document that has the specified identifier (id \u003d "ElementID"), as an Node (node) object. If the item with the specified identifier does not exist, this method returns the NULL value.

In accordance with the standard, you cannot have several elements with the same id attribute value, i.e. The identifier value must be unique within one document. However, if you have several items with the specified ID in the document, 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 attribute value of the element ID you want to receive.

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

Article title

  • 1 point
  • 2 point
  • 3 Point

Method GetElementsByClassName ()

The GetElementSBYCLASSNAME (ClassName) method returns all the found items in the document (for Document) or among the child nodes (for NODE) \u200b\u200bwith the specified class name (class \u003d "classname"), as an Nodelist object. In other words, this method returns an Nodelist object, which is a collection of elements (nodes) that have the name of the class specified in the parameter method.

To obtain the number of nodes found, you must use the Nodelist Length property. And in order to move all the nodes in the collection, you can use the following cycle:

Var elementslist \u003d document.getelementsbyclassname ("List"); for (var i \u003d 0; i

document.getelementByClassName (Classname);
Node (node) .gelementByClassName (ClassName);

This method has one required parameter (ClassName), which is a string containing the name of the class of the elements you want to receive. If you want to get elements with several specified classes, they must be divided into the parameter of this method using a space. For example, get a collection of nodes having CLASSL classes and Class2:

Document.getelementsByClassName ("Classl Class2");

For example, change the color of the background of elements having a LIST class:

Article title

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

For example, to obtain a collection of elements (nodes) having a LIST class. Next to get 2 knots in this collection, i.e. Node Having index 1. After that, change the background color of the obtained node.

// Get a collection of elements with the List VAR ElementSlist \u003d Document.getelementSBYCLASSNAME class ("List"); // Get 2 nodes in the collection Var Secondlist \u003d Elementslist; // Change the background color of the secondlist.style.backgroundcolor \u003d "red" element;

Method GetElementsByTagname ()

The GetElementSbyTagname (TagName) method returns all the found items in the document (for Document) or among the child nodes (for NODE) \u200b\u200bwith the specified tag, in the form of the Nodelist object (collection of nodes). Receiving a specific node in the collection is carried out by index. Counting elements (nodes) in the collection begins with 0.

document.getelementsByTagname (TagName);
Node (node) .gelementsBytagname (TagName);

This method has one mandatory parameter (tagname), which is a string containing the name of the tag that is indicated by uppercase letters. If you specify a string containing the starrel ("*") as a parameter, then we will get all the items in the document (for the Document object) or all child elements of the node (for the NODE object).

To obtain the number of nodes found in the collection, you must use the Nodelist Length property. And in order to move all the nodes in the collection, you can use the following cycle:

Var elementslist \u003d document.getelementsbytagname ("Li"); for (var i \u003d 0; i

For example, change the color of the background of Li elements:

Article title

  • 1 point
  • 2 point
  • 3 Point

For example, get a collection of UL elements. Next, get 1 node in this collection, i.e. Node Having index 0. After that, to obtain a collection of Li's subsidiaries for this node. And in conclusion, change the font size of each element in this collection.

// Get a collection of elements UL VAR Elementsul \u003d Document.getelementsBytagname ("UL"); // Get 1 node in this collection VAR Elementul \u003d Elementsul; // Get a collection of child elements Li Elementul Var Elementsli \u003d elementul.gelementsli \u003d elementul.getelementsbytagname ("Li"); // Loose all the items in the for (var i \u003d 0; I

Method GetElementsByname ()

Method GetElementsByname (Name) Returns all found items in the document that have the specified name (Name attribute value), as an object Nodelist (nodes collection).

Elements (nodes) are added to the collection in the order in which they are found in the tree. Receiving a specific node in the collection is carried out by index. Counting elements (nodes) in the collection begins with 0.

Var elementslist \u003d document.getelementsbyname ("Phone"); for (var i \u003d 0; i

Note: In HTML5, the NAME attribute is recognized as obsolete, and it has been replaced for most elements ID attribute.

document.getelementsByname (Name)


This method has one mandatory parameter (Name), which is a string containing the Name attribute value.

For example, change the background color of the items having the Name attribute with the phone value (name \u003d "phone"):

Phone: Another Phone:

QuerySelector () method

The QuerySelector () method returns the first element found in the document (for Document) or among the child nodes (for Node), which corresponds to the CSS selector specified as the parameter of this method. If no item corresponds to the CSS selector, then this method returns NULL.

document.QuerySelector (CSSSselector)
Node.QuerySelector (CSSSselector)

This method has one mandatory parameter (CSSSselector), which is a string containing the CSS selector, in accordance with which the element is selected.

For example, change the color of the text of the first found element corresponding to the #main P selector:

...

...

For example, to obtain a collection of DIV elements in the document. Next, get 1 node in this collection, i.e. A node Having index 0. For this node, the first element, which corresponds to the CSS selector H1 + P, is found among its subsidiary nodes. After that, change the font size of this item.

// Get a collection of Div Var ElementSdiv \u003d Document.getelementsBytagname elements ("DIV"); // Get 1 node in this collection VAR ElementDiv \u003d Elementsdiv; // Get a node P, located immediately after the h1 node // search node to produce among the subsidiaries of the node, which is stored in the ElementDiv var Elementp \u003d elementdiv.QuerySelector variable ("H1 + P"); // Resize the element font elementp.style.fontsize \u003d "30px";

QuerySelectorall ()

The QUERYSELECTORAL () method returns all the found items in the document (for Document) or among the child nodes (for NODE), which correspond to the CSS selector specified as the parameter of this method, as an Nodelist object (collection of nodes). Appeal to nodes in the collection is carried out by index. Counting elements (nodes) in the collection begins with 0.

To obtain the number of nodes found, it is necessary to use the Nodelist Length property. And in order to move all the nodes in the collection, you can use the following cycle:

Var elementslist \u003d document.queryselectorall ("# Main P"); for (var i \u003d 0; i

document.QuerySelectorall (CSSSselector);
Node (knot) .QuerySelectorall (CSSSselector);

This method has one mandatory parameter (CSSSselector), which is a string containing the CSS selector, in accordance with which elements are selected. To specify multiple selectors in the parameter of this method, they must be divided into a comma.

For example, change the color of the text of the elements corresponding to the #main P selector:

...

...

For example, get a child node having an ID attribute with the Sidebar value. Change the color of the background of the subsidiary elements P node obtained at the previous step:

// Get an item (node), which has id \u003d "Sidebar" var sidebar \u003d document.getelementbyid ("Sidebar"); // Get a collection of nodes corresponding to the selector "P" VAR Elementslistp \u003d sidebar.queryselectorall ("P"); // Loose all the items in the for (var i \u003d 0; I

The task

Write code in JavaScript Using GeTelementByid (), GetElementsByClassName (), GetElementsByTagname (), GetElementSBYTagname (), QuerySelector (), QuerySelectorall () for the following tasks:

  1. Get all elements p located in the Main block;
  2. Get the ASIDE block located in the DIV container;
  3. Get the Footer block located in the Body container.

Each task is to perform as much of different methods as possible.

As you know - in the development of a voluminous JS application where the most popular JQuery library comes when the performance problem is sharp. All the forces are thrown on the ambrusura of the profiler, each challenge scrupulously was investigated, each functionally loaded piece of sale of snug-in from all sides and is intended. But the trouble does not come from the other side, from where 90% of developers are waiting for it. Selectors - How much of this word.
Let's figure out - how this magic works and why the search for DOM elements can cause the application productivity drop.

How jQuery disassembles the selector

In the library itself to search for items, the SIZZLE engine has a number of features. We will look at them.
querySelectorall ()
In the new browsers, an excellent queryselectorall () and queryselector () function appeared, which knows how to search for elements using browser capabilities (in particular - used when viewed CSS and assign properties to elements). This feature does not work in all browsers, but only in FF 3.1+, IE8 +. (only in standard IE8 mode), Opera 9.5+(?) and Safari 3.1+. So SIZZLE always defines the presence of this function and trying any search to perform through it. However, here not without surprises - for the successful use of QuerySelectorall (), our selector must be valid.
I will give a simple example:
The two premium selectors are practically no different and return the same set of elements. However, the first selector will return the result of the operation of QuerySelectorall (), and the second is the result of normal filtering by items.
$ ("# MY_FORM INPUT")
$ ("# MY_FORM INPUT")
Selector analysis and search
If you failed to use QuerySelectorall (), the SIZZLE will try to use the usual GetElementByid () browser (), GetElementsByname (), GetElementsByTagname () and GetElementByClass (). In most cases, they are enough, but (SIC!) In IE< 9 getElementByClassName() поломана и использование селектора по классу приведёт к полному перебору элементов в этом браузере.
In the general case, Sizzle disassembles the selector to the right left. To illustrate this feature, I will give a few examples:
$ ("Divs .my_class")
First, elements will be found .My_class, and then only those that have.divs are filtered in parents. As we see, this is a pretty cost operation, and the use of the context does not solve the problem (we will talk about the context below).
As I said - in most cases, SIZZLE will disassemble the selector to the right left, but not in case of using an element with ID:
$ ("# Divs .my_class")
In this case, the selector will behave as expected and immediately will be taken element #divs for use in the form of a context.
Context
The second parameter transmitted together with the selector to the function $ () is called the context. He is designed to narrow the range of finding elements. However, when parsing the context docks to the beginning of the selector, that the winning does not allow the win. The winning context use combination is a valid selector for queryselectorall (), since this function can be applied not only on behalf of the Document, but also from the item. Then the selector with the context is shaped transformed the following design:
$ (". Divs", document.getelementByid ("Wrapper"));
Document.getelementByid ("Wrapper"). QuerySelectorall ("Divs"); // if you have the opportunity to use QuerySelectorall ()

In this example, if it is not possible to use QuerySelectorall (), SIZZLE will filter the elements by simple bust.
Another remark about the context (not about selectors) - if the second parameter in the selector for the function.live () is the jQuery object - the event will be caught on Document (!), And if the DOM object is to pop up an event only to this item . Such subtleties I try not to memorize, but I use .Delegate ().

Filters and hierarchy elements
To search for nested elements, you can use the following selector:
$ ("Root\u003e .Child")
As we know - the sealer's parsing and the search will begin on all.Child elements on the page (provided that the queryselectorall () is not available). Such an operation is quite cost and we can transform the selector as:
$ (". Child", $ (". root")); // Context Use will not facilitate the search
$ (". root"). Find (". Child"); // Why do we need to bust all the elements inside .root?
$ ("Root"). Children (". Child"); // The most correct option

However, if there is a need to use filters for any attributes (: visible,: EQ, etc.) and the selector looks like this:
$ (". Some_Images: Visible")
The filter will be applied last time - i.e. We again retreat from the rule "right to left".

RESULTS
  • If possible, use the right selectors suitable for QUERYSELECTORALL ()
  • Replace subordination inside selectors for subqueries (.children (...), etc.)
  • Specify the context of the selector
  • Filter as a smaller finished element set
Fast selectors in the new year! All in the coming!

Based on master class

Object model document - DOM - this is nothing but a tree structure consisting of tags existing in HTML. Document.

We have all these elements HTML.Located next to each other we want to get, and then read the data in them or change. There are many ways to find these tags, as they are located in the tree structure. In this article you will learn how to use two built-in functions. Javascript., such as the querySelector. and querySelectorall. For search hTML tags.

QuerySelector method

To understand the essence of the methods of methods querySelector. and querySelectorall. Look at the next HTML:















In this example we have one div with identifier main. and four elements invested in it div and img, each of which has the value of the class pic-Container and profileimage. respectively. In the following few sections, we apply functions. querySelector. and querySelectorall. On this HTML code And let's see what happens.

querySelector.

Function querySelector. Works as follows:

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

QuerySelector feature takes an argument, and this argument is CSS selector For the item you want to find. Returns querySelector feature, It is the first element that it finds, even if there are other elements that can be similar to this selector.

Looking at HTML. From our previous example, if we want to access divwhose identifier is main.You need to write the following:

Var element \u003d document.QuerySelector ("# Main");

Insofar as main. is the identifier, the syntax of the selector to obtain it will be #Main. . Similarly, a class selector pic-Container :

Var element \u003d document.queryselector (". Pic-Container");

The first block is returned div , whose value is pic-Container . Other elements div Class pic-Container Just ignored.

The syntax of selectors for this function was not created specifically, so you can use the exact syntax that you would use for selectors in the style sheet!

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

JavaScript, like CSS, has a functionality that allows you to access HTML items to convert page content. In CSS it is achieved by writing selectors. In JavaScript there are several ways to organize this functionality, and here is one of them:

Var primaryheads \u003d document.getelementsbytagname ("h1");

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

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

This code selects an item with ID \u003d "EDDIE".

Var Guitars \u003d Document.getelementsByClassName ("Axes");

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

Add a little sizzle

A different kind of JavaScript Freymworks will provide their own capabilities of selectors. One of the most successful was Sizzle, which later transformed into jQuery. Unlike his descendant, Sizzle could only work with DOM and manipulate them. If you do not need the rest of the jQuery functionality, then today you can download SIZZLE as a separate library.

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

$ ("# Dave"). CSS ()

This code retrieves the HTML item 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, for example, Rangy. However, in my opinion, all the above is outdated before that it expects you further in this article.

New level javascript

Many developers have often begun to use jQuery, which did not even notice the cardinal changes in the JavaScript itself.

"JavaScript SELECTOR API" is the official part of the HTML5 specification, it can be used and when writing XHTML pages. The new syntax is very simple:

Document.QuerySelector ("# EDDIE")

This code is an absolutely equivalent 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. To extract all you need to use QuerySelectorall:

Var Hifrets \u003d Document.QuerySelectorall ("Table # Frets TR: NTH-Child (3)")

This code retrieves each third line from the table with id \u003d "Frets".

Several very important points

There are several restrictions on which you should know if you use the QuerySelector / All method:

Not all browsers support new features. If it is important for you to work on IE6-7, it is better to use libraries that can manipulate the DOM: SIZZLE or JQuery.

The selectors must be prepared very carefully, otherwise the 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 extracted elements in the form in which they are on the page at the moment. This means that when making any dynamic changes to the code (adding, deleting items via JavaScript), it will be necessary to take advantage of the QuerySelectorAll method.

Try new features to get rid of the need to download various kinds of library.

Last updated: 1.11.2015

To work with the DOM structure in JavaScript, the Document object is intended, which is defined in the Global Window object. The Document object provides a range of properties and methods for managing page elements.

Search elements

The following methods are applied to search for items on the page:

    getElementByid (Value): Selects an element in which the ID attribute is equal to Value

    getElementsByTagname (Value): Selects all the elements that the tag is equal to Value

    getElementsByClassName (Value): Chooses all the elements that have the Value class

    querySelector (Value): Selects the first element that corresponds to the VALUE CSS selector

    querySelectorall (Value): Selects all the items that match the CSS selector Value

For example, find an element by ID:

Using the Call Document.getelementByid ("Header") we find an item from which id \u003d "Header". And using the InNERTEXT property, you can get the text of the found item found.

Search by a specific tag:

Title

First paragraph

Second paragraph

Using the document.getelementSBYTAGNAME call ("P"), we find all the elements of paragraphs. This call returns an array of found items. Therefore, to get separate elements of the array, you need to run on them in the cycle.

If we only need to get the first element, you can go to the first element of the found collections of objects:

Var PELEMENT \u003d Document.getelementsBytagname ("P"); Document.Write ("Sext Paragraph:" + pelement.innertext);

Getting an element in the class:

Title Articles

First paragraph

Second paragraph

Selection of CSS selector:

Abstract article

First paragraph

Second paragraph

The document.QuerySelector expression (". Annotation P") finds an element that corresponds to the selector.annotation p. If the page has several items corresponding to the selector, the method will select the first one. As a result, the browser will withdraw:

Annotation Article First paragraph Second paragraph Text of the selector: Abstract article

To get all the elements on the selector, you can like the Document.QuerySelectorAll method, which returns the array of the found items:

Abstract article

First paragraph

Second paragraph

Browser output:

Annotation Article First paragraph second paragraph Text selector 0: First paragraph Text selector 1: Second paragraph