Как получить элемент по id javascript
Перейти к содержимому

Как получить элемент по id javascript

  • автор:

How to get DOM elements using JavaScript

The Document Object Model (DOM) is a programming interface for HTML and XML documents created by the browser once the document is loaded. A web page is a document represented by the DOM as nodes and objects. It allows programs to manipulate the document's content, structure, and styles.

In this tutorial, we shall learn how to use JavaScript to access different nodes (HTML elements) in the DOM. Let us start with the first method: getting an element by ID.

The document 's getElementById() method takes the element ID as input and returns an Element object representing the DOM element. Here is an example:

Now here is how we can get the above <div> element by using its ID:

The ID is case-sensitive and unique across the entire HTML document. So this method always returns a single element. If no matching element is found, it returns null .

Note: Do not put the # sign before the ID string while calling getElementById() method. You will get null instead of the element, and then you might wonder for hours what has gone wrong.

The getElementsByTagName() method is used to access multiple elements. It takes the tag name as input and returns all of the DOM elements that match the tag name as HTMLCollection :

JavaScript code to access all <p> elements:

This method searches only one tag name at a time. But if you pass in * as the tag name, you will get all elements in the DOM:

The getElementsByName() method is used to get a collection of elements by their name attribute and returns a NodeList object:

Let us get all the elements with the name email :

Note: Unlike the id attribute, which must be unique, multiple HTML elements can have the same name attribute. That's why getElementsByName() returns a collection of nodes.

Want to use the class attribute to get a list of matching elements? You can use the getElementsByClassName() method, pass it a class name (without . ), and it will return an HTMLCollection of all DOM elements that have the given class name:

Let us get all the birds:

This method also accepts multiple class names separated by spaces. Let us get all elements that have both the bird and eagle classes:

The querySelector() method is one of the two modern JavaScript methods that allow you to get elements from DOM based on CSS selectors. Just pass in the CSS selector, and you will get the first element that matches the specified selector. If no matches exist, it returns null . Here is an example:

Want to select a list of elements that match the specified selectors? Use the querySelectorAll() method instead. This method takes multiple CSS selectors as input and returns a NodeList , a list of DOM elements that match the given selectors. Let us select all elements with a class of either bird or animal from the above HTML markup:

You can also chain multiple functions together to search elements within another element. You first need to select a single element using either getElementById() or querySelector() and then chain another function to search within:

Get all input elements inside of an element that has the ID signup :

Most of the methods we discussed above (except getElementById() and querySelector() ) returns multiple elements as either an HTMLCollection or a NodeList .

The HTMLCollection is not an array but a generic collection of elements. So it is impossible to iterate over it with the forEach() or map() method. However, we can convert it to a real array and then iterate using the Array.from() method:

Although NodeList is also not an array, it does provide the forEach() method to iterate over the elements:

That's all for getting DOM elements using JavaScript. We have learned about many different methods to access the DOM elements: using the id attribute, HTML tag name, name attribute, class attribute, and CSS selectors. We also discussed ways to iterate over the generic collection of elements returned by these methods.

✌️ Like this article? Follow me on Twitter and LinkedIn. You can also subscribe to RSS Feed.

How To Access Elements in the DOM

In Understanding the DOM Tree and Nodes, we went over how the DOM is structured as a tree of objects called nodes, and that nodes can be text, comments, or elements. Usually when we access content in the DOM, it will be through an HTML element node.

In order to be confident in accessing elements in the DOM, it’s good to have a working knowledge of CSS selectors, syntax and terminology as well as an understanding of HTML elements. In this tutorial, you will learn several ways to access elements in the DOM: by ID, class, tag, and query selectors.


Here is a table overview of the five methods we will cover in this tutorial.

Gets Selector Syntax Method
ID #demo getElementById()
Class .demo getElementsByClassName()
Tag demo getElementsByTagName()
Selector (single) querySelector()
Selector (all) querySelectorAll()

It is helpful when studying the DOM to work with the examples on your own to ensure that you are understanding and retaining the information you learn.

Create a new file, access.html , in your own project to work through the examples along with this article. If you are unsure how to work with JavaScript and HTML locally, review our How To Add JavaScript to HTML tutorial.

In this HTML file, we have many elements that we will access with different document methods. When we render the file in a browser, it will look similar to this:

Browser rendering of access.html page

We’ll be using the different methods that we outlined in the Overview above to access the available elements in the file.

Accessing Elements by ID

The easiest way to access a single element in the DOM is by its unique ID. You can get an element by ID with the getElementById() method of the document object.

In order to be accessed by ID, the HTML element must have an id attribute. You have a div element with an ID of demo you can use:

In the Console, get the element and assign it to the demoId variable.

Logging demoId to the console will return our entire HTML element.

You can be sure you’re accessing the correct element by changing the border property to purple .

Once you do so, your live page will look like this:

Browser rendering of ID element styling

Accessing an element by ID is an effective way to get an element quickly in the DOM. However, it has drawbacks: an ID must always be unique to the page, and therefore you will only ever be able to access a single element at a time with the getElementById() method. If you wanted to add a function to many elements throughout the page, your code would quickly become repetitious.

Accessing Elements by Class

The class attribute is used to access one or more specific elements in the DOM. You can get all the elements with a given class name with the getElementsByClassName() method.

Now we want to access more than one element, and in our example we have two elements with a demo class.

Access these elements in the Console and put them in a variable called demoClass .

At this point, it might be tempting to modify the elements the same way you did with the ID example. However, if you try to run the following code and change the border property of the class demo elements to orange, you will get an error.

The reason this doesn’t work is because instead of just getting one element, you have an array-like object of elements.

JavaScript arrays must be accessed with an index number. You can change the first element of this array by using an index of 0 .

Generally when accessing elements by class, we want to apply a change to all the elements in the document with that particular class, not just one. You can do this by creating a for loop, and looping through every item in the array.

When you run this code, your live page will be rendered like this:

Browser rendering of class element styling

You have now selected every element on the page that has a demo class, and changed the border property to orange .

Accessing Elements by Tag

A less specific way to access multiple elements on the page would be by its HTML tag name. You access an element by tag with the getElementsByTagName() method.

For our tag example, we’re using article elements.

Just like accessing an element by its class, getElementsByTagName() will return an array-like object of elements, and you can modify every tag in the document with a for loop.

Upon running the code, the live page will be modified like so:

Browser rendering of tag element styling

The loop changed the border property of all article elements to blue .

Query Selectors

If you have any experience with the jQuery API, you may be familiar with jQuery’s method of accessing the DOM with CSS selectors.

You can do the same in plain JavaScript with the querySelector() and querySelectorAll() methods.

To access a single element, you can use the querySelector() method. In our HTML file, we have a demo-query element

The selector for an id attribute is the hash symbol ( # ). You can assign the element with the demo-query id to the demoQuery variable.

In the case of a selector with multiple elements, such as a class or a tag, querySelector() will return the first element that matches the query. You can use the querySelectorAll() method to collect all the elements that match a specific query.

In the example file, you have two elements with the demo-query-all class applied to them.

The selector for a class attribute is a period or full stop ( . ), so you can access the class with .demo-query-all .

Using the forEach() method, you can apply the color green to the border property of all matching elements.

Browser rendering of querySelector() styling

With querySelector() , comma-separated values function as an OR operator. For example, querySelector(‘div, article’) will match div or article , whichever appears first in the document. With querySelectorAll() , comma-separated values function as an AND operator, and querySelectorAll(‘div, article’) will match all div and article values in the document.

Using the query selector methods is extremely powerful, as you can access any element or group of elements in the DOM the same way you would in a CSS file. For a complete list of selectors, review CSS Selectors on the Mozilla Developer Network.

Complete JavaScript Code

Below is the complete script of the work you did above. You can use it to access all the elements on our example page. Save the file as access.js and load it in to the HTML file right before the closing body tag.

Your final HTML file will look like this:

You can continue to work on these template files to make additional changes by accessing HTML elements.


In this tutorial, we went over 5 ways to access HTML elements in the DOM — by ID, by class, by HTML tag name, and by selector. The method you will use to get an element or group of elements will depend on browser support and how many elements you will be manipulating. You should now feel confident to access any HTML element in a document with JavaScript through the DOM.

Thanks for learning with the DigitalOcean Community. Check out our offerings for compute, storage, networking, and managed databases.

Tutorial Series: Understanding the DOM — Document Object Model

The Document Object Model, usually referred to as the DOM, is an essential part of making websites interactive. It is an interface that allows a programming language to manipulate the content, structure, and style of a website. JavaScript is the client-side scripting language that connects to the DOM in an internet browser.

What are the different ways to select DOM elements in JavaScript?

Many candidates are rejected or down-leveled due to poor performance in their System Design Interview. Stand out in System Design Interviews and get hired in 2023 with this popular free course.

In this shot, we will learn different ways to select a DOM element in JavaScript.

Let’s say our elements are as follows:

JavaScript provides six methods to select an element from the document.

  • getElementById – search element by element_id
  • getElementsByTagName – search element by tag name (e.g., span, div)
  • getElementsByClassName – search element by class name
  • getElementsByName – search element by name attribute
  • querySelector – returns the first element that matches the specified selector
  • querySelectorAll – returns elements that match the specified selector

What is the getElementById method?

The getElementById method returns an element whose id matches a passed string.

Since the ids of elements are supposed to be unique, this is a faster way to select an element. The getElementById method is only available in the document object because, since id values must be unique, there is no need for a separate function.

If the id is not found, then this method returns null .

What is the getElementsByTagName method?

The getElementsByTagName method returns the HTMLCollection of elements that match the passed tag name.

Unlike getElementByID , getElementsByTagName can be called on any element. If getElementsByTagName is called upon an element, then only children of the element are searched.

The returned HTMLCollection is a live list that automatically updates node removal or addition.

If you pass * (universal selector), then it selects all the elements.

The tag name passed is lower-cased internally before searching for elements. So, for svg elements, use getElementsByTagNameNS() .

What is the getElementsByClassName method?

The getElementsByClassName method returns an HTMLCollection of elements that match the passed class name.

We can search for multiple class names by passing the class names separated by whitespace.

getElementsByClassName can be called on any element and will return a live HTMLCollection.

What is the getElementsByName method?

The getElementsByName method returns the elements that match the value of the name attribute with the passed string. The return value is a live NodeList Collection.

It is not recommended to use getElementByName because it works differently on Internet Explorer.

What is the querySelector method?

The querySelector method returns the first element that matches the passed selector.

  • querySelector can be called on document and element. If no elements match the selector, null is returned.
  • SyntaxError is thrown when the CSS selector is invalid.

Multiple selectors can be specified by separating them using commas.

What is the querySelectorAll method?

The querySelectorAll method is an extension of the querySelector method. This method returns all the elements that match the passed selector.

  • querySelectorAll returns static (non-live) NodeList Collection.
  • This method can be called on both document and element.
  • We can send multiple selectors separated by commas.
  • If no matches are found, an empty NodeList is returned.

The elements in NodeList are stored in the order present in the DOM.

To learn about how querySelectAll is different from other libraries, check out the official documentation.

Get element by part of Name or ID

Here is an example of my form (only inputs that I want, but there is many others):

What I want is to get values of inputs, but as the form is built in PHP, I don’t know the line identifier (77, 108).

Is there a way to do something like getElementByName(‘id_qtedje_%’) ?

Note: I’m not using any library, and I don’t plan to use one.

pistou's user avatar

2 Answers 2

Your best bet is probably document.querySelectorAll , which you can use any CSS selector with, including an «attribute starts with» selector like input[id^=»id_qtedje_»] . It’s supported on all modern browsers, and also IE8:

If you wanted just the first match (rather than a list), you could use document.querySelector instead. It returns a reference to the first match in document order, or null if nothing matched.

Alternately, you could give the elements a class name, then use document.getElementsByClassName , but note that while getElementsByClassName was supported in old versions of Chrome and Firefox, IE8 doesn’t have it, so it’s not as well-supported as the more-useful querySelectorAll in the modern era.

If you use any libraries (jQuery, MooTools, Closure, Prototype, etc.), they’re likely to have a function you can use to look up elements by just about any CSS selector, filling the gaps in browser support with their own code. For instance, in jQuery, it’s the $ ( jQuery ) function; in MooTools and Prototype, it’s $$ .

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *