简体   繁体   中英

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);
}

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM