JavaScript JavaScript Basics

How to Add an ID to Element with Javascript

Spread the love

We can add an ID to a given element with JavaScript.

To do this, first we get the element. We can use the following methods:

  • document.querySelector
  • document.querySelectorAll
  • document.getElementById
  • document.getElementsByTagName

We probably want to use anything other than getElementById since our element doesn’t have an ID yet.

document.querySelector can get an element with any CSS selector and return it.

For instance, given that we have an element with class foo, we can write:

const el = document.querySelector('.foo');

With querySelectorAll, it returns a NodeList with all elements with the given CSS selector.

So we’ve to find the one that’s right for us. But assuming that we want the first element, we can write:

const el = document.querySelectorAll('.foo')[0]

With getElementsByTagName, we can get all the elements by their tag name.

For instance, we can write:

const el = document.getElementsByTagName('div')[0]

to get all the divs with the given name.

In all cases, we can get an HTMLElement object, which has the id property, which we can use to set the ID of an element by assigning a string to it.

We can write: = 'bar';

to set the ID of el above to bar.

The id property of an HTMLElement can be set to let us add an ID to the element of our choice with JavaScript.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *