Add an id attribute to an element using JavaScript

Add an id attribute to an element using JavaScript

Posted by Ervin Adams on June 28, 2022

Add an id attribute to an element using JavaScript

Add an id attribute to an element using JavaScript

Posted by Ervin Adams on June 28, 2022

To add an id attribute to element:

  • Use the setAttribute(name, value) 
  • The first param will specify the name of the attribute 
  • The second param is a string continaing the value to assign to the attribute
  • Use  document.querySelector() to select the element

For example:

CSS

#bg{background:blue}

HTML

<p class="note">give me background color</p>

JavaScript

const note = document.querySelector(".note");

note.setAttribute("id", "bg");

So, in the above example the background color is set using the id "bg".

Notice "bg" is set using the setAttribute() function.

Obviously you might need a more dynamic senario to use a technique like this.

Like when a button is clicked add the id attribute or somehting to that effect.