A task that is very often faced by novice javascript developers is selecting an element on a web page by its id attribute.

Let's say we have code on a page.

Block content.

How can I select an element with id="elem" and perform some actions with it?

There are several options for solving the problem here. Let's take a 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 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 this script to work, 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 loaded, i.e. it will not be in the code at the time of the script execution. 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 we can solve this problem in a different 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, which is called Jquery, then this library must first be connected.

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

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

Block content.

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

Thus, we have analyzed two ways 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.


In the last lesson, the getElementsByTagName method was considered, which returns an array ( group) page elements by tag name.

Here goes on practical work with javascript and the getElementById method will be considered which is returns a reference to an element, based on its unique id .

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

The name of the method is translated literally: get element by id.

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

pay attention e: 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 the element.

Some explanation for the code snippet above...

  • img tag ( images f) has id - the identifier penguin ;
  • using the getElementById method, this img tag is selected by the penguin identifier;
  • into a variable unique link is entered to the selected tag;
  • then you can work with the tag, as with an object through a variable unique , just like working with the Date object through an arbitrary variable.

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

Therefore, attribute values ​​are already property values.

Let's continue with the previous example...

"Pensive Penguin">

Explanations for the example code...

  • img tag ( images f) has certain attributes: src - file address, width and height - image width and height, alt - alternative text;
  • having accessed the tag using the getElementById method as an object, we get access to the tag's attributes, how to object properties;
  • BUT 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 you are not confused by all this. You need to understand at the same time what is happening at the javascript program level and at the document markup level.

The img tag is a unique Object;

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

Attribute values ​​"128" and "Pensive Penguin" are property values;

// Here's what it looks like from a javascript perspective:

var unique = (

width : "128" ,

alt : "Pensive Penguin"

}

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

It should be taken into account 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 of a web document.

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, the script accesses the element and performs some actions with it.

Search by id

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

document.getElementById(id)

Options:

id - the id of the element to be found. id is a string, so it must be in quotes.

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

HTML code:

JavaScript:

var block = document.getElementById("block"); console log(block);

We assigned the found element to the block variable and displayed the variable in the console. Open the browser console, it should contain the element.

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

Search by class

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

document.getElementsByClassName(class)

Options:

class - class of elements to be found

The method returns a pseudo-array containing the found elements. It is called a pseudo-array because many array methods do not 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. Some of the elements will be placed inside the block that we created earlier. The other part will be created outside the block. The meaning of this will become clear a little later. Now the page will look like this:

HTML code:

JavaScript:

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

Search by tag

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

document.getElementsByTagName (tag)

Options:

tag - tag of elements to be found

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

var p = 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 given selector. That is, elements will be found to which the style would have been applied if it had been specified to such a selector. At the same time, the presence of such a selector in the page style is not necessary at all. 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, which is the first element 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 don't forget 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 one, because it is the 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 within a single element.

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

Adjacent 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 child elements block.

In addition to allowing web pages to select elements by their id, we can also select elements by their class attribute.

The task is also very common. When I write my scripts, I have to use this selector very often.

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

Block content.

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

Let's look at a few options for how this can be done.

Option 1: Use the Javascript getElementsByClassName method.

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

For example, in relation to 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.

Please note that the result of the getElementsByClassName method execution 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") construction, you need to indicate that the zero element of the array () is displayed. Counting in Javascript 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 it's redundant code. For example, you can use regular expressions:

If(document.getElementsByClassName == undefined) ( document.getElementsByClassName = function(cl) ( var retnode = ; var myclass = new RegExp("\\b"+cl+"\\b"); var elem = this.getElementsByTagName( "*"); for (var i = 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 solve 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 construct:

$(".elem")

Here elem is the class name assigned to the element.

It must be remembered 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:

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

Let's see how this works with an example.

Block content.

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

Thus, there are two ways in which you can interact with elements that have the class attribute set. Choose the one that suits you best and use it in practice.

Property matches the specified string. Since element IDs are required to be unique if specified, they"re a useful way to get access to a specific element quickly.

If you need to get access to an element which doesn't have an ID, you can use querySelector() to find the element using any selector .

Syntax

var element = document.getElementById(id);

Parameters

id The ID of the element to locate. The ID is case-sensitive string which is unique within the document; only one element may have any given ID.

return value

An Element object describing the DOM element object matching the specified ID, or null if no matching element was found in the document.

example

HTML

getElementById example

Some text here

JavaScript

function changeColor(newColor) ( var elem = document.getElementById("para"); elem.style.color = newColor; )

result

Usage notes

The capitalization of "Id" in the name of this method must be correct for the code to function; getElementByID() is not valid and will not work, however natural it may seem.

Unlike some other element-lookup methods such as Document.querySelector() and Document.querySelectorAll() , getElementById() is only available as a method of the global document object, and not available as a method on all element objects in the DOM. Because ID values ​​must be unique throughout the entire document, there is no need for"local" versions of the function.

example

document

hello word1

hello word2

hello word3

hello word4

If there is no element with the given id , this function returns null . Note that the id parameter is case-sensitive, so document.getElementById(" M ain") will return null instead of the element

because "M" and "m" are different for the purposes of this method.

Elements not in the document are not searched by getElementById() . When creating an element and assigning it an ID, you have to insert the element into the document tree with or a similar method before you can access it with getElementById() :

var element = document.createElement("div"); element.id = "testqq"; var el = document.getElementById("testqq"); // el will be null!

Non-HTML documents. The DOM implementation must have information that says which attributes are of type ID. Attributes with the name "id" are not of type ID unless so defined in the document"s DTD. The id attribute is defined to be of ID type in the common cases of XHTML , XUL , and other. Implementations that do not know whether attributes are of type ID or not expected to return null .

Specification

Specification Status Comment
Document Object Model (DOM) Level 1 Specification
Obsolete Initial definition for the interface
Document Object Model (DOM) Level 2 Core Specification
The definition of "getElementById" in that specification.
Obsolete Supersede DOM 1
Document Object Model (DOM) Level 3 Core Specification
The definition of "getElementById" in that specification.
Obsolete Supersede DOM 2
DOM
The definition of "getElementById" in that specification.
Living Standard Intend to supersede DOM 3

Browser compatibility

The compatibility table on this page is generated from structured data. If you"d like to contribute to the data, please check out https://github.com/mdn/browser-compat-data and send us a pull request.

Update compatibility data on GitHub

DesktopMobile
ChromeedgeFirefoxInternet ExplorerOperasafariandroid webviewChrome for AndroidFirefox for AndroidOpera for AndroidSafari on iOSSamsung Internet
getElementByIdChrome Full support 1Edge Full support 12Firefox Full support 1IE Full support 5.5Opera Full Support 7Safari Full support 1WebView Android Full support YesChrome Android Full support 18Firefox Android Full supportYesOpera Android Full support 10.1Safari iOS Full support 1Samsung Internet Android ?

Legend

Full support Full support Compatibility unknown Compatibility unknown