本文介绍了可以使用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吗?
发布评论