Menor
Menor

Reputation: 300

Displaying information from an array list in javascript

I have a list of driver names, that is displayed on my page and I want to get more information about the driver when I click on the name. I am struggling with running a function. Here's what my html looks like:

<main>
<nav id="list">

</nav>
<section id="profile">

</section>

That's my list:

const drivers = [{
  name: "data",
  age: "data1",
  nationality: "data2"
}]

And that's the function I am trying to run:

function driverProfile(drivers) {
  const article = document.createElement('article');
  const span = document.createElement('span');
  const h2 = document.createElement('h2');

  h2.textContent = drivers[driver_id].nationality;
  span.textContent = drivers[driver_id].age;
  article.textContent = drivers[driver_id].name;
 }

 myProfile = driverProfile(drivers)
 profile.appendChild(myProfile)

I get this error Uncaught TypeError: Failed to execute 'appendChild' on 'Node': parameter 1 is not of type 'Node'. pointing to profile.appendChild(myProfile)

My list function:

drivers.forEach(addLink);

function addLink(driver, index) {
  const a = document.createElement('a');
  a.href = `?driver=${index}`;
  a.textContent = driver.name;
  list.appendChild(a);
}

Upvotes: 0

Views: 56

Answers (2)

Ritesh Khandekar
Ritesh Khandekar

Reputation: 4005

It is better practice to group elements. First append elements in div then append new divs to section:

function driverProfile(drivers) {
  const div = document.createElement("div");
  const article = document.createElement('article');
  const span = document.createElement('span');
  const h2 = document.createElement('h2');

  h2.textContent = drivers[driver_id].nationality;
  span.textContent = drivers[driver_id].age;
  article.textContent = drivers[driver_id].name;
  div.appendChild(h2);
  div.appendChild(span);
  div.appendChild(article);
  return div;
 }

 myProfile = driverProfile(drivers);
 profile.appendChild(myProfile);

The program give error because your function is not of return type and you are assigning function to myProfile variable.

appendChild function takes html elements as Object but you had given function. Just change function to return type as shown in above code.

Upvotes: 2

Tech Solver
Tech Solver

Reputation: 523

driverProfile is not returning any node. At the end of this function you need to return the node you want to be appended.

Upvotes: 0

Related Questions