简体   繁体   中英

Unable to change value of an element in array

Here's the code:

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

worked perfect. But, here's the second part:

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>

So, I couldn't change the value at elements[0] . Why this is happening? How can I change it without using temp variable like temp = elements[0]; temp = temp.parentNode; console.log(temp); temp = elements[0]; temp = temp.parentNode; console.log(temp); ?

querySelectorAll returns NodeList not an Array . If you need to mutate it further convert it to array

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

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

The "funny" part is: the readonly behaviour is not crossbrowser.

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

Chrome UPD Chrome is lying about NodeList property. It is readonly and enumerable.

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

FF

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

IE - who cares? IE is telling truth. Properties are writable.

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

Looks like as per 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.

Strangely enough, assigning new values to any index doesn't change the values unless you do

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

Now, it returns the value you are looking for.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM