Reputation: 187
I would like to understand if I can treat a HTMLCollection as an constand using const keyword (ES6) or better treat as a variable using the var keyword.
What´s making me getting confudes is the fact, that const buttons is changing in the for-loop, but beeing accessed over the array-like object.
(function IIFE() {
'use strict';
const buttons = document.getElementsByTagName('button');
for (let i = 0, l = buttons.length; i < l; i += 1) {
buttons[i].onclick = function () {
for (let i = 0; i < l; i += 1) {
buttons[i].className = '';
this.className = 'active';
}
};
}
console.log(typeof(buttons)); // object
console.log(buttons); // HTMLCollection
}());
ul {
list-style-type: none;
width: 196px;
padding: 10px 20px;
margin-left: auto;
margin-right: auto;
}
li {
display: inline-block;
}
button {
font-size: 34px;
font-weight: 900;
font-family: , "andale mono";
border-radius: 4px;
margin-right: 20px;
}
.active {
background: rgba(51, 181, 229, 0.4);
}
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Test UI</title>
<link href="style.css" rel="stylesheet">
</head>
<body>
<ul>
<li><button class="active">A</button></li>
<li><button>B</button></li>
<li><button>C</button></li>
</ul>
<script src="script.js"></script>
</body>
</html>
Upvotes: 1
Views: 154
Reputation: 68433
What´s making me getting confudes is the fact, that const buttons is changing in the for-loop, but beeing accessed over the array-like object.
const
keyword only prevents you from changing the value (primitive or reference) of the variable. You can still modify the properties of the variable.
So you can't do the following
const buttons = document.getElementsByTagName('button');
buttons = document.getElementsByTagName('button');//this line will throw an error with or without const again
But you can do the following
const buttons = document.getElementsByTagName('button');
buttons[0].className = ''; //only property is being modified not the object reference value itself
Upvotes: 3