unix_root unix_root - 3 months ago 6x
HTML Question

Unable to change value of an element in array

Here's the code:


<div id="ID1">
<a href="www.google.com">click</a>
<a href="www.yahoo.com">click</a>


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
. Why this is happening? How can I change it without using
variable like
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}


// { 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}