Reputation: 23
I want to make li
elements with properties like below but it doesn't work at all. Could you help me with what is wrong?
var array = [1, 2, 3, "mm", "b", "c", "mm", "y", "mm"];
var list = document.getElementById("list");
function addText(array) {
for (var i = 0; i <= array.length; i++); {
var text = array[i];
if (array[i] == "mm") {
var listItem = document.createElement("LI");
listItem.innerHTML = text;
list.appendChild(listItem);
}
}
};
Upvotes: 0
Views: 6665
Reputation: 91
There are at least two reasons why your code might not work.
your for loop is not doing much other than incrementing var i. You should remove the semicolon after the for loop. Change it to this:
for (var i = 0; i <= array.length; i++) {
When are you calling your javascript? If you're running document.getElementById before you define the element with id "list" then document.getElementById("list") will return undefined.
One solution is to define the script at the end of your body, such as:
<body>
<ul id="list">
</ul>
<script type="text/javascript">
var array = [1, 2, 3, "mm", "b", "c", "mm", "y", "mm"];
function addText(array) {
var list = document.getElementById("list");
for (var i = 0; i <= array.length; i++) {
var text = array[i];
if (array[i] == "mm") {
var listItem = document.createElement("LI");
listItem.innerHTML = text;
list.appendChild(listItem);
}
}
};
window.onload = function(){ addText(array) };
</script>
</body>
Upvotes: 0
Reputation: 71
var array = [1, 2, 3, "mm", "b", "c", "mm", "y", "mm"];
var list = document.getElementById("list");
function addText(array) {
array.map(function(element) {
if(element === 'm'){
var listItem = document.createElement('LI');
listItem.textContent = element;
list.appendChild(listItem);
}
});
}
addText(array);
<ul id="list">
</ul>
Upvotes: 0
Reputation: 16012
The semicolon at the end of the for loop is the problem.
for (var i = 0; i <= array.length; i++); // <-- remove this
The semicolon makes the loop do nothing for array.length + 1 times instead of looping through the code in between the braces. You also want to change the <=
to <
so that you don't exceed the array boundary. Arrays are zero based, so your array of 9 items have indices from 0-8. You can also just compare text
instead since you're copying it to a variable (not sure what was your intent since you can just get rid of the temporary outright).
Also, since you're just adding text, use textContent
over innerHTML
Demo:
var array = [1, 2, 3, "mm", "b", "c", "mm", "y", "mm"];
var list = document.getElementById("list");
function addText(array) {
for (var i = 0; i < array.length; i++) {
var text = array[i];
if (text == "mm") {
var listItem = document.createElement("LI");
listItem.textContent = text;
list.appendChild(listItem);
}
}
}
addText(array);
<ul id="list">
</ul>
Upvotes: 4
Reputation: 96
What is the type of list element. It should be a "ul" element for that to achieve what you need.
Upvotes: -1