JavaScript - DOM: methods for finding nodes. Javascript and Jquery selectors. Selecting an element by id Properties and attributes of the document object in javaScript

The DOM standard provides several means of finding an element. These are getElementById, getElementsByTagName, and getElementsByName.

Javascript libraries offer more powerful search methods.

Search by id

The most convenient way to find an element in the DOM is to get it by id. To do this, call document.getElementById (id)

For example, the following code will change the text color to blue in the div "e c id \u003d" dataKeeper ":

Document.getElementById ("dataKeeper"). Style.color \u003d "blue"

Search by tag

The next way is to get all the elements with a specific tag and search for the desired one among them. This is what document.getElementsByTagName (tag) is for. It returns an array of elements that have this tag.

For example, you can get the second element (the numbering in the array starts from zero) with the li tag:

Document.getElementsByTagName ("LI")

Interestingly, getElementsByTagName can be called not only for document, but in general for any element that has a tag (not text).

This will only find objects that are under this element.

For example, the following call gets a list of LI elements that are inside the first div tag:

Document.getElementsByTagName ("DIV"). GetElementsByTagName ("LI")

Get all descendants

Calling elem.getElementsByTagName ("*") will return a list of all children of the elem node bypassing them.

For example, on a DOM like this:

Code like this:

Var div \u003d document.getElementById ("d1") var elems \u003d div.getElementsByTagName ("*") for (var i \u003d 0; i

Will print the sequence: ol1, li1, li2.

Search by name: getElementsByName

The document.getElementsByName (name) method returns all elements whose name (name attribute) is equal to the given one.

It works only with those elements for which the specification explicitly provides a name attribute: these are form, input, a, select, textarea, and a number of others, more rare.

The document.getElementsByName method will not work with other elements like divs, p, etc.

other methods

There are other ways to search the DOM: XPath, cssQuery, etc. Typically, they are implemented by javascript libraries to extend the standard browser capabilities.

There is also a getElementsByClassName method for finding elements by class, but it does not work at all in IE, so no one uses it in its pure form.

A common typo is due to the absence of a letter s in the method name getElementById, while in other methods this letter is: getElement sByName.

The rule here is simple: one element is an Element, many are an Element. s ... All * Element methods s* return a list of nodes.


The last lesson covered the getElementsByTagName method, which returns an array ( group) page elements by tag name.

Here's a little more practical work with javascript and the getElementById method, which returns a reference to the element, focusing on its unique id.

The getElementById method, like getElementsByTagName, is a method of the document object.

The method name translates literally: get element by id.

Any element ( tegu) of the web document can be assigned its own id-identifier, thanks to which the element becomes unique and you can access it to work with it.

Pay attentione: there is no s in the method name at the end of the word Element ( as opposed to the getElementsByTagName method). This is for convenience and indicates that the method is used to select an item.

A bit of clarification for the code snippet above ...

  • img tag ( imagesf) has an id - identifier penguin;
  • using the getElementById method, this img tag is selected by the penguin identifier;
  • into a variable unique link is entered on the selected tag;
  • then you can work with the tag, as with an object through a variable unique, similar to how you worked with the Date object through an arbitrary variable.

After accessing the element ( tegu) web page by id-identifier using the getElementById method, we are already working with it as an Object, which means we get access to the attributes of the tag as to the properties of the Object.

Therefore, the attribute values \u200b\u200bare already property values.

Let's continue working with the previous example ...

"Thoughtful Penguin">

Explanations for the example code ...

  • img tag ( imagesf) has certain attributes: src - file address, width and height - image width and height, alt - alternative text;
  • by accessing the tag using the getElementById method as an object, we access the tag's attributes, how to object properties;
  • A attribute values are now property values;
  • in javascript, object properties are accessed through a dot. Next, we display alt - the alternative text of the img tag using the alert method on the screen.

I hope that you are not confused in all this. You need to understand at the same time what is happening at the programmatic level of javascript and at the level of document markup.

The img tag is a unique Object;

The tag's width and alt attributes are properties of the Object;

Attribute values \u200b\u200b"128" and "Thoughtful Penguin" - these are property values;

// This is how it looks from a javascript perspective:

var unique \u003d (

width: "128",

alt: "Thoughtful Penguin"

}

This is how the getElementById method works, which returns a reference to any element ( tag) of a web page if it has a unique id. Next, we work with this element at the javascript level. already as with an object...

It should be noted that: as in the previous lesson, here - when working with the getElementById method, the script call line should be placed at the end of the html-document

JQuery provides other options for selecting elements in a web document.

Besides the fact that on web pages you can select elements by their id, we can also select elements by the class attribute.

The task is also very common. When I write my scripts, I use this selector a lot.

Let's assume we have the following code on a page.

Block content.

The task is simple, you need to select an element with the class \u003d "elem" and perform some actions with it using Javascript.

Let's look at a few options on how to do this.

Option 1. Use the Javascript getElementsByClassName method.

If you do not use any additional libraries, you can access the element using the getElementsByClassName ("class_name") method.

For example, referring to the source code, you can add the following lines of code.

Block content.

As a result, if everything works correctly, we will get a pop-up window in which the text that is inside the div block will be displayed.

Note that the result of executing the getElementsByClassName method will be an array of elements. there can be several elements with the same class on the page.

That is why at the end of the document.getElementsByClassName ("elem") structure, you need to indicate that the zero element of the array () is displayed. Javascript counting starts at zero, not one.

But the problem with using the getElementsByClassName method is that this method is not supported in older versions of browsers.

There are some tricks to get around this, but this is extra code. For example, you can use regular expressions:

If (document.getElementsByClassName \u003d\u003d undefined) (document.getElementsByClassName \u003d function (cl) (var retnode \u003d; var myclass \u003d new RegExp ("\\\\ b" + cl + "\\\\ b"); var elem \u003d this.getElementsByTagName ( "*"); for (var i \u003d 0; i< elem.length; i++) { var classes = elem[i].className; if (myclass.test(classes)) { retnode.push(elem[i]); } } return retnode; } };

This is one way to fix the problem. But, to be honest, it is not very acceptable for me to clog the page with unnecessary code, so most often I use the second solution to the problem.

Option 2. Using the Jquery library.

Using the Jquery library makes it much easier to solve the problem of selecting elements by their class attribute. You need to use the construction:

$ (". elem")

Here elem is the class name assigned to the element.

Remember that in order for this to work, the Jquery library must first be included. 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.

Let's see how this works with an example.

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, here are two ways you can interact with elements that have the class attribute set. Choose the one that suits you best and use it in practice.

The task that very often confronts novice 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, 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.

Last updated: 1.11.2015

To work with the DOM structure in JavaScript, the document object is defined, which is defined in the global window object. The document object provides a number of properties and methods for manipulating page elements.

Find items

The following methods are used to find elements on a page:

    getElementById (value): Selects an element whose id attribute is value

    getElementsByTagName (value): Selects all elements with tag equal to value

    getElementsByClassName (value): Selects all elements that have class value

    querySelector (value): selects the first element that matches the value css selector

    querySelectorAll (value): Selects all elements that match the value css selector

For example, let's find an element by id:

Call document.getElementById ("header") to find the element with id \u003d "header". And using the innerText property, you can get the text of the found element.

Search for a specific tag:

Title

First paragraph

Second paragraph

Call document.getElementsByTagName ("p") to find all paragraph elements. This call returns an array of found elements. Therefore, to get the individual elements of the array, you need to go through them in a loop.

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

Var pElement \u003d document.getElementsByTagName ("p"); document.write ("Paragraph text:" + pElement.innerText);

Getting an element by class:

Article title

First paragraph

Second paragraph

Selecting by css selector:

Abstract of the article

First paragraph

Second paragraph

The document.querySelector (". Annotation p") expression finds the element that matches the .annotation p selector. If there are several elements on the page that match the selector, then the method will select the first one. As a result, the browser will display:

Article abstract First paragraph Second paragraph Selector text: Article abstract

To get all elements by a selector, you can similarly use the document.querySelectorAll method, which returns an array of found elements:

Abstract of the article

First paragraph

Second paragraph

Browser output:

Article abstract First paragraph Second paragraph Selector text 0: First paragraph Selector text 1: Second paragraph