我可以使用 Javascript 更改 HTML 元素的 ID 吗?
我有 javascript 变量 obj ,它代表 DOM 中的一个元素,我希望更改它的 ID。我尝试通过以下方式做到这一点,这也说明它不起作用!
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! }
我上面的代码有什么问题,这意味着 id 似乎已更改但未在 DOM 中获取?非常感谢。
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(7)
您的代码看起来不错,但如果您在代码中以这种方式进行注释,您可以意识到大括号永远不会由于注释而关闭。
Your code looks fine, although if you are commenting that way in your code, you can realize that the brace is never closed due to the comment.
试试这个:
对我有用
Try this:
Works for me
还有一件事需要考虑。您是否想在 DOM 准备好之前执行此操作?该元素加载了吗?如果您尝试更改 DOM 树中没有的元素,您将悄悄失败。
There's another thing to consider. Are you trying to do this before the DOM is ready? Is that element loaded yet? If you try to change an element that the DOM doesn't have in the tree you will quietly fail.
是的,你可以,这是一个使用 jquery
或的解决方案
Yes you can, here is a solution with jquery
or
由于您没有给我们完整的代码,我的猜测是您的代码中可能有类似的内容
在这种特殊情况下,
document.getElementById("newID")
不会返回任何内容由于该元素未添加到页面,因此在页面中找不到它。Since you haven't give us the whole code my guess is that you probably have something similar to this in your code
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.您显示的代码确实有效;问题可能出在查找并分配 obj 的代码中。我的猜测是,这只是一个 javascript 对象,而不是 DOM 树的一部分。
The code you show does work; the problem is probably in the code which looks up and assigns
obj
. My guess is that this is just a javascript object, not a part of the DOM tree.没有理由不使用纯 JavaScript 来实现这一点。这是一个工作小提琴,显示它正在工作。您不需要 jQuery 解决方案或任何其他 JavaScript 方法,
id = "foo";
是更改 DOM 对象 ID 的最简单方法。看看我上面的小提琴,尝试看看你的代码和我的代码有什么区别。
There's no reason this shouldn't work using pure JavaScript. Here's a working fiddle that shows it working. You shouldn't need a jQuery solution or any other JavaScript method,
id = "foo";
is the simplest way of changing a DOM Objects ID.Take a look at my above fiddle and try and see what's the difference between your code and mine.