Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
60 views
in Technique[技术] by (71.8m points)

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.

question from:https://stackoverflow.com/questions/1650299/how-do-i-change-the-id-of-a-html-element-with-javascript

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...