I am trying to learn JS Dom Manipulation, and while tinkering along the code, I learnt that the "for in" loop is hiding the last li element "Zathura" (before creation. But the traditional "for" loop doesn't do that, can someone explain what is happening?
- This is how the page looks like without any loop, Zathura is added with JS.
- This is traditional for loop and that's what I wanted with the below for in.
- But this is what I get when I run the for in, Zathura goes away.
- Adding the for in to the bottom of the Zathura creation fixes it, can someone explain what's happening?
5.Whole code:
<html lang="en">
<head>
<style>
.licolor{
color: blue;
font-size: 1.5rem;
}
</style>
<title>ManipulatingDom</title>
</head>
<body>
<div id="container">
<h1>Fav Movies</h1>
<ul>
<li class="list">Harry Potter</li>
<li class="list">John wick</li>
<li class="list">Interstellar</li>
<li class="list">Wolverine</li>
</ul>
</div>
<script defer>
// DOM MANIPULATION
// STYLING ELEMENTS
const list = document.querySelectorAll('.list');
// Traditional for loop works fine, this is what I'm trying to achieve with the for in below.
// for(let i=0;i<list.length;i++){
// list[i].style.color='blue';
// list[i].style.fontSize='1.5rem'
// }
// for..in.. this hides the last li which i'm adding by js, why though?
for(let each in list){
list[each].style.color='blue';
list[each].style.fontSize='1.5rem';
}
// CREATING Last LI ELEMENT
const ul= document.querySelector('ul');
const li= document.createElement('li');
ul.append(li);
li.innerText = 'Zathura';
li.classList.add('licolor');
// this fixes it, but is it hoisting issue or something can someone explain why above traditional for loop is working properly and not for in, and here it works fine.
// for(let each in list){
// list[each].style.color='blue';
// list[each].style.fontSize='1.5rem';
// }
</script>
</body>
</html>