可以使用Javascript更改HTML元素的ID吗?

编程入门 行业动态 更新时间:2024-10-09 13:22:08
本文介绍了可以使用Javascript更改HTML元素的ID吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述 我有一个javascript变量obj,它表示DOM中的一个元素,我想改变它的ID。我试图通过以下这样做,这也说明它不起作用。

obj.id =newID ; alert(obj.id); //这给我newID作为需要 var element = document.getElementById(newID); if(element!= null){alert(Hooray); //这个警报永远不会显示! }

我的代码上面有什么问题,这意味着id似乎被改变了,但没有被拾起在DOM中?非常感谢您提前。

解决方案

您显示的代码可以工作;问题可能在查找并分配 obj 的代码中。我的猜测是,这只是一个javascript对象,而不是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.

解决方案

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更改HTML元素的ID吗?

本文发布于:2023-10-26 18:04:10,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1530926.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:可以使用   元素   HTML   Javascript   ID

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!