文档对象模型值如何由上次更改的值填充?



在学习DOM时,我写了下面的脚本:

console.log(document);//how this will generate the last update id value
var x = document.getElementById("old").getAttribute("id");
var y = document.getElementById("old").setAttribute("id","IDChanged");
console.log(document);
<div id="old">first</div>

两个结果都是:

<div id="IDChanged"><div>

运行此代码片段后,我发现两个结果都在生成具有相同ID的HTML文档,即IDCHANGED,而我期望的是第一个控制台.log将生成一个带有div的文档,其ID为old,第二个console.log将生成divID为IDChanged的文档。

那么,如何做这项工作呢?

当您对div元素真正更感兴趣时,您正在记录document对象(出于某种原因没有意义)。我不知道你为什么说你看到IDChanged记录了两次,而你的console.log()语句都不会产生,它们都会记录document对象,而不是div

如果您删除了第一个console.log()并将最后一个更改为:

console.log(x,y);

你会看到你想要的结果,但实际上,忘记document,专注于div。我认为这就是您正在寻找的,以查看更改前后的id

// Get a refernece to the div
var x = document.querySelector("div");
// Report the contents of the document before doing anything:
console.log(x);
// Change the ID of the element
x.setAttribute("id","IDChanged");
// Report the contents of the document after DOM manipulation:
console.log(x);
<div id="old">first</div>

最新更新