0

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

2 Answers 2

2

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.

Sign up to request clarification or add additional context in comments.

Comments

0

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

3 Comments

can you give me some example?
when I am trying to return one value it works, but when i do return {article, h2, span}; it throws the same error
Each item in that list is a node. But you are return a bunch of nodes which is not correct. You need to return only one.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.