1

How do I create a function accepts two parameters, the first is a list element that should be added to, the second is an array of strings that will be turned into list items.

The parameters were the element and the arr. I tried to create the list element and append the array strings into the element using appendChild.

function filler(elem, arr){
  elem = document.createElement("li");
  for(let i = 0; i < arr.length; i++){
    elem.appendChild(arr[i]);
  }
}

Error message:

Failed to execute 'appendChild' on 'Node': parameter 1 is not of type 'Node'.

Nick Parsons
  • 45,728
  • 6
  • 46
  • 64
Stephen Adams
  • 225
  • 1
  • 2
  • 8

2 Answers2

1

You have a few issues:

  1. You're reinitializing elem within your function, so, the elem passed through will be overwritten, meaning you won't be able to append elements to it.

  2. You're trying to append a string to your elem element. This won't work as you need to append a node (as appendChild() accepts a node, not a string). To append a node, you can create a <li> HTML element in your JS by using document.createElement("li"), which you can then set the text to be that of your current array value (using .textContent).

See example below:

function filler(elem, arr){
  for(let i = 0; i < arr.length; i++){
    const li = document.createElement("li");
    li.textContent = arr[i];
    elem.appendChild(li);
  }
}

const lst = document.getElementById('lst');
filler(lst, ["eggs", "bread", "butter"]);
<ul id="lst"></ul>
Nick Parsons
  • 45,728
  • 6
  • 46
  • 64
0

Fill the elements and return the full list.

function filler(elem, arr){
  for(let i = 0; i < arr.length; i++){
    listItem = document.createElement('li');
    listItem.innerHTML = arr[i];
    elem.appendChild(listItem);
  }
  return elem;
}

Here is a use case filler(document.createElement('ul'), ['a', 'b', 'c']);

Olawale Akinseye
  • 177
  • 1
  • 1
  • 13