Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I change the ID of an HTML element using Javascript?

I have javascript variable obj which represents an element in the DOM and I wish to change its ID. I have attempted to do this by the following, which also illustrates that it does not work!

obj.id = "newID";

alert(obj.id); // this gives me newID as required

var element = document.getElementById("newID");

if (element != null) { alert("Hooray"); // this alert never gets displayed! }

What is wrong with my code above that means that the id seems to be changed but not picked up in the DOM? Many thanks in advance.

like image 384
user455141 Avatar asked Sep 24 '10 13:09

user455141


People also ask

Can you change ID of HTML 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.

What is a correct way to get an HTML element by its ID in JavaScript?

Document.getElementById() The Document method getElementById() returns an Element object representing the element whose id property matches the specified string.


1 Answers

Since you haven't give us the whole code my guess is that you probably have something similar to this in your code

obj = document.createElement("div");
obj.id = "something";

// ...

obj.id = "newID";

alert(obj.id); // this gives me newID as required

var element = document.getElementById("newID");

if (element != null) { alert("Hooray"); // this alert never gets displayed! }

In that particular case, document.getElementById("newID") won't return you anything since the element wasn't added to the page and therefore it is not found in the page.

like image 68
HoLyVieR Avatar answered Sep 19 '22 22:09

HoLyVieR