javascript - 无法更改数组中元素的值

标签 javascript html arrays element

代码如下:

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/

相关文章:

HTML定位

css - 展开 div 以使用 css 获得剩余宽度

c - 为什么我的代码会导致段错误?

Javascript用特殊字符替换子字符串中的所有内容

javascript - 拍摄并显示图像

javascript - 将参数传递给 casperjs.start

java - 如何初始化和打印数组中的各个元素

javascript - 匹配jquery数据属性后获取子元素

链接上的 jQuery 单击以启用加载图形

ios - 如何过滤包含字符串和数组的结构?