代码如下:
HTML:
<div id="ID1">
<a href="www.google.com">click</a>
</div>
<a href="www.yahoo.com">click</a>
JS:
var element = document.querySelector("a[href^='www.google.com']");
console.log(element); // this returns the <a> object
element = element.parentNode;
console.log(element); // this returns the <div> object
工作完美。但是,这是第二部分:
var elements = document.querySelectorAll("a[href^='www.google.com']");
console.log(elements[0]); //this returns <a> object
elements[0] = elements[0].parentNode;
console.log(elements[0]); //this returns <a> instead of <div>
因此,我无法更改 elements[0]
的值。为什么会这样?如何在不使用 temp
变量的情况下更改它,例如 temp = elements[0]; temp = temp.parentNode; console.log(temp);
?
最佳答案
querySelectorAll
返回 NodeList
不是数组
。如果您需要对其进行变异,请进一步将其转换为数组
var elements = [].slice.call(document.querySelectorAll("a[href^='www.google.com']"))
elements[0] = elements[0].parentNode;
console.log(elements[0]); //div
“有趣”的部分是:只读行为不是跨浏览器。
Object.getOwnPropertyDescriptor(document.querySelectorAll('a'), '0')
Chrome UPD Chrome 对 NodeList 属性撒谎。它是只读的和可枚举的。
// {value: a, writable: true, enumerable: false, configurable: true}
全速
// { value: <a>, writable: false, enumerable: true, configurable: true }
IE - 谁在乎? IE说的是实话。属性是可写的。
// {configurable: true, enumerable: true, value: HTMLAnchorElement {...}, writable: true}
关于javascript - 无法更改数组中元素的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38306886/