无法更改数组中元素的值

Unable to change value of an element in array

代码如下:

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 = elements[0]; temp = temp.parentNode; console.log(temp); 之类的 temp 变量的情况下更改它?

querySelectorAll returns NodeList 不是 Array。如果您需要对其进行变异,请将其进一步转换为数组

var elements = [].slice.call(document.querySelectorAll("a[href^='www.google.com']"))

elements[0] = elements[0].parentNode;
console.log(elements[0]); //div

"funny"部分是:只读行为不是跨浏览器。

Object.getOwnPropertyDescriptor(document.querySelectorAll('a'), '0')

Chrome UPD Chrome 关于 NodeList 属性 的谎言。它是只读的和可枚举的。

// {value: a, writable: true, enumerable: false, configurable: true}

FF

// { value: <a>, writable: false, enumerable: true, configurable: true }

IE - 谁在乎? IE说的是实话。属性是可写的。

// {configurable: true, enumerable: true, value: HTMLAnchorElement {...}, writable: true}

看起来符合 docs

In other cases, the NodeList is a static collection, meaning any subsequent change in the DOM does not affect the content of the collection. document.querySelectorAll returns a static NodeList.

奇怪的是,为任何索引分配新值都不会更改值,除非您这样做

elements = [].slice.call(elements);
elements[0] = elements[0].parentNode;
console.log(elements[0]); //this returns <a> instead of <div>

现在,它 returns 您正在寻找的值。