How to Add an ID to an HTML Element With JavaScript

With this neat code snippet you can add an ID attribute to any existing HTML element by using JavaScript.


The Code

let featuredTitle = document.querySelector("h1");
featuredTitle.id = "featured-title";

Here’s what’s happening in the video:

  • First, we find the h1 element on the web page and assign it to a variable called featuredTitle.
  • Then we attach an ID attribute to that variable via dot notation (variableName.attribute) in this case: featuredTitle.id and give it a value of 'featured-title'.

You can do this to any existing element in the DOM.

Now you can use this dynamically created ID to hook on to either with CSS (to style the element via its new ID) or with JavaScript for handling interactive behavior (like click events).


Has this been helpful to you?

You can support my work by sharing this article with others, or perhaps buy me a cup of coffee 😊

Kofi

Share & Discuss on