I've created a nodeList of list elements using createElement(). Then I've used Array.from() to convert the nodeList in question into array I can iterate over. I want to apply a different width according to the value of the index. If index is even width of 300px else width of 500px. However, the console returns "Cannot read property 'style' of undefined at bottlesOnTheWall".
I've also used [...] to turn my nodeList into an array but without success either. My guess is that is not a nodeList in the first place, which means it can't be converted into an array. At least not using either of these approaches.
I was wondering if someone could point out where I've gone wrong and fix my code. I've been spending more time that's healthy trying to do so.
const bottles = document.getElementById("bottles");
count = 99;
var myArray = [];
var j = 0;
function bottlesOnTheWall() {
while (count > 0) {
if(count > 2) {
myArray.push(`${count} bottles of beer on the wall, ${count} bottles of beers. Take one down and pass it around, ${count - 1} bottles of beer on the wall`)
} else if (count === 2) {
myArray.push(`${count} bottles of beer on the wall, ${count} bottles of beers. Take one down and pass it around, ${count - 1}bottle of beer on the wall`)
} else if (count === 1) {
myArray.push(`${count} bottle of beer on the wall, ${count} bottles of beers. No more bottle of beer on the wall`)
} else {
myArray.push(`No more bottles of beer on the wall. No more bottles of beer. Go to the shop and buy some ${count} more.`)
}
count--
}
while (j < myArray.length) {
var liElement = document.createElement("li");
var text = document.createTextNode(myArray[j]);
liElement.appendChild(text);
bottles.appendChild(liElement);
var bottlesArray = Array.from(bottles);
if(j % 2) {
bottlesArray[j].style.width = "300px";
} else {
bottlesArray[j].style.width = "500px";
}
j++;
}
}
bottlesOnTheWall();
#bottles {
line-height: 2;
letter-spacing: 3px;
}
/* ul {
list-style-image: url('beer.png');
} */
body {
background: #FFF8DC;
}
li {
max-width: 500px;
margin: auto;
margin-bottom: 10px;
}
ul li {
background: #FFEBCD;
}
<!DOCTYPE html>
<html lang="en" dir="ltr">
<head>
<meta charset="utf-8">
<title>bottles on the wall</title>
<link rel="stylesheet" href="index.css">
</head>
<body>
<ul id="bottles" ></ul>
<script src="index.js" type="text/javascript"></script>
</body>
</html>
const bottles = document.getElementById("bottles");returns a node, not a nodelist.Array.from(bottles)therefore tries to convert a node to an array.bottlesArray[j].style.width = "some width";means you're converting to an array just to get the last indexjout of it. It can probably just beliElement.style.width = "some width";if you want the last appended element.