How to add an ID to element in JavaScript

IDs are essential in JavaScript. They refer to a particular element compatible with the getElementById() method, which returns it with the given property.

IDs should be unique within a page, and all elements within a page should have an ID even though it is not necessary.

You can add an ID to a new JavaScript Element or a pre-existing HTML Element.


svg viewer

Adding ID to a pre-existing HTML element

First, you need to find the element. This can be done using:

  • document.getElementsByTagName()

  • document.getElementsByClassName()

  • document.querySelectorAll()

Once you have the element, you can edit its contents with the following code:

var intro = document.getElementsByClassName(‘intro’);intro.setAttribute(‘id’, ‘Introduction_ 1’)

Adding ID to a new HTML element

First, create a new element. This can be done within HTML or with JavaScript. Use:

const terms = document.createElement(‘p’);

This will create a new element to store a paragraph. Then, use the following to assign an id:

terms.setAttribute(‘id’,‘para-1’);

You can also add multiple other attributes such as:

terms.setAttribute(‘class’, ‘Class-s-m-x’);

This method will assign the id para-1 to the element and move it to the Class-s-m-x class so that the appropriate formatting can be applied.

Using HTML

You can add an id using HTML by typing the following:

<p id= “para-1” class= “Class-s-m-x”>

This method helps declare the ids and class names while developing the frontend. It is used to quickly apply the same formatting to multiple elements of the same class.

Coding example

Now, let's interact with a coding example by clicking the "Run" button in the below widget.

Copyright ©2024 Educative, Inc. All rights reserved