Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does querySelectorAll sometimes return live DOM elements?

Tags:

javascript

querySelectorAll doesn't return live DOM elements. However unless I'm missing something this isn't true for all properties.

Question: I tested querySelectorAll with the .innerHTML property. Instead of returning the number 5 that was present when the document was created it returned the word FIVE that was inserted with Javascript. Why is this?

As a control I tested querySelectorAll with the .length property and it returned the number 10 as anticipated.

I must be missing a key concept about querySelectorAll but I'm not sure what that is. My code is below. Thanks so much!

var largeContainer = document.querySelectorAll(".box_1");
		
document.getElementsByClassName("box_1")[9].className = "box_2";				
console.log(largeContainer.length);
		
document.getElementsByClassName("box_1")[5].innerHTML = "FIVE";  
console.log(largeContainer[5].innerHTML);
.box_1 {
  height: 100px;
  margin: 0 0 16px 0;
  font-size: 2rem;
  color: white;
  background-color: red;
}

.box_2 {
  height: 100px;
  margin: 0 0 16px 0;
  font-size: 2rem;
  color: white;
  background-color: blue;
}
<div class="box_1">0</div>
<div class="box_1">1</div>
<div class="box_1">2</div>
<div class="box_1">3</div>
<div class="box_1">4</div>
<div class="box_1">5</div>
<div class="box_1">6</div>
<div class="box_1">7</div>
<div class="box_1">8</div>
<div class="box_1">9</div>
like image 253
DR01D Avatar asked Sep 28 '26 00:09

DR01D


2 Answers

As per the documentation, you are correct that it returns a static NodeList i.e. the set of elements it did select during installation doesn't change.

However, these Elements in the NodeList are references to the existing DOM elements (live nodes). Hence any change to those elements will be reflected in subsequent access.

like image 169
Abhilash Nayak Avatar answered Sep 29 '26 12:09

Abhilash Nayak


Well, var largeContainer = document.querySelectorAll(".box_1"); selects all DOM elements with the class box_1. If you change the class later, largeContainer is still referring to those DOM elements, not the selector that was once used to get them.

like image 40
Nick Avatar answered Sep 29 '26 14:09

Nick



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!