Unable to change item value in array
Here is 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 fine. But here is 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 could not change the value in elements[0]. Why is this happening? How can I change it without using a variable templike temp = elements[0]; temp = temp.parentNode; console.log(temp);?
+4
2 answers
querySelectorAllreturns NodeListno Array. If you need to mutate, then it will convert it to an 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: readonly behavior is not a crossbrowser.
Object.getOwnPropertyDescriptor(document.querySelectorAll('a'), '0')
Chrome UPD Chrome is about the NodeList property. It is read only and we list.
// {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}
+2