Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I change the ID of a HTML element with JavaScript?

I am modifying the ID of an HTML div element client side with JavaScript. The following code works OK in Internet Explorer but not in Firefox/2.0.0.20. It does work in more recent versions of Firefox.

document.getElementById('one').id = 'two';

Can anyone tell me:

  1. Why this doesn't work in FireFox.
  2. How to make this work in FireFox.

To clarify, I'm changing the element ID to reference a different style in an external style sheet. The style is applied in IE but not in FF.

like image 287
Tesseract Avatar asked Oct 30 '09 14:10

Tesseract


People also ask

Can you change HTML ID with JavaScript?

Given an HTML document and the task is to change the ID of the element using JavaScript. There are two approaches that are discussed below: Approach 1: We can use the id property to change the ID using JavaScript.

How do you change an HTML element using JavaScript?

To change HTML element type with JavaScript, we can use the replaceWith method. For instance, we write: const parent = document. createElement("div"); const child = document.

How JavaScript can change HTML attribute values?

To change the attribute value of an HTML element HTML DOM provides two methods which are getAttribute() and setAttribute(). The getAttribute() is used to extract the current value of the attribute while setAttribute() is used to alter the value of the attribute.

Can I change ID of an element?

To change the id attribute of an HTML element, you can use the jQuery attr() method which allows you to set an element's attribute value. You can change any HTML element id attribute value by using the example above as a reference.


1 Answers

It does work in Firefox (including 2.0.0.20). See http://jsbin.com/akili (add /edit to the url to edit):

<p id="one">One</p>
<a href="#" onclick="document.getElementById('one').id = 'two'; return false">Link2</a>

The first click changes the id to "two", the second click errors because the element with id="one" now can't be found!

Perhaps you have another element already with id="two" (FYI you can't have more than one element with the same id).

like image 54
Roatin Marth Avatar answered Sep 23 '22 08:09

Roatin Marth