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:
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.
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.
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.
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.
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.
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
).
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