1

<div id="content">
  Content
</div>

How would I change the ID of this div using Javascript?

Obsidian Age
  • 41,205
  • 10
  • 48
  • 71
user3858703
  • 111
  • 2
  • 3
  • 6

2 Answers2

11

Found this on the first result on a Google search:

document.getElementById("originalDivId").setAttribute("id", "newDivId");

getElementById does exactly what it says, it obtains the information of an element with the Id specified. setAttribute changes a HTML element's attribute, that is the stuff inside of the HTML tags (e.g. class="", id="", style="", etc).

aimorris
  • 436
  • 3
  • 18
1

You can replace a <div> element's ID with .setAttribute("id", "newID"). This replaces the ID attribute of the target element with the value specified in the second parameter.

Here's an example showcasing this, changing the ID original to modified, and logging the change to the console:

console.log(document.getElementById("original").id);
document.getElementById("original").setAttribute("id", "modified");
console.log(document.getElementById("modified").id); // The same element
<div id="original">
  Content
</div>

Note that you have to re-target with document.getElementById("modified") once the change has been applied.

Hope this helps! :)

Obsidian Age
  • 41,205
  • 10
  • 48
  • 71