unix_root unix_root - 4 months ago 20
HTML Question

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);
?

Answer

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}