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.
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.
Document.getElementById() The Document method getElementById() returns an Element object representing the element whose id property matches the specified string.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With