HOWTO · JavaScript

How to Add ID to Element Using JavaScript

This tutorial demonstrates how to add an ID attribute to an HTML element using JavaScript. Learn various methods, including using setAttribute and directly assigning the ID property. Discover practical code examples and detailed explanations to enhance your web development skills. Perfect for beginners and experienced developers alike.

On this page

To add or change an HTML element’s ID, select the element and assign a value with either element.setAttribute('id', 'profile') or element.id = 'profile'. The new value replaces any ID already on that element. Use an ID that is unique in the document.

Add an ID to an existing element

Select an existing element with its current ID, then set the new value. For example, if the page contains <h2 id="intro">Introduction</h2>, select that actual HTML element with const heading = document.getElementById('intro') and change its ID with heading.setAttribute('id', 'article-title'). Its .id property then contains article-title; use document.getElementById('article-title') to find it by the new ID later.

The following standalone JavaScript demonstration uses a plain object to show the same assignment and its printed value. It does not select or modify an HTML element; use the DOM code above when working with a page:

const element = { id: 'intro' };
element.id = 'article-title';
console.log(element.id);
article-title

setAttribute() takes an attribute name and value, so it can also set attributes other than id.

An ID should identify one element in the document. If another element already uses article-title, choose a different value to keep the IDs unique.

Add an ID to a new element

Create the element with document.createElement('p'), assign note.id = 'status-note', then append it with document.body.append(note). Creating a node alone does not display it on the page. This adds the paragraph to the end of the document body; set its text or other attributes before appending it when those values should be present as it enters the document.

Choose between setAttribute() and the id property

For an element’s ID, assigning element.id = 'profile' is direct and concise. Calling element.setAttribute('id', 'profile') uses the general attribute method and is useful when code already handles attribute names dynamically. Both set the same ID; you do not need to call both. The .id property returns the element’s current ID, so it is also a straightforward way to read the value.

Add an ID with jQuery

If jQuery is already loaded on the page, select the element and set its ID with $('#intro').attr('id', 'article-title'). This changes the selected element’s ID to article-title, just as the native DOM examples do. The $ selector and .attr() method require jQuery to be included in the page; without that library, use the native JavaScript methods above.