Otonye Amietubodie
Otonye Amietubodie

Reputation: 15

trying to display an array of object on my screen in vanilla javascript

please i am new to javaScript. i am trying to display the items inside of the data array on my screen after i click on the add task button. i can the data inside my console but when i loop over it and try and render it on my screen i get this error Uncaught TypeError: Cannot read properties of null

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link rel="stylesheet" href="./index.css">
    <title>Document</title>
</head>
<body>
    <div class="container">
        <input id="nameInput" placeholder="enter name" >
        <input id="jobInput" placeholder="enter job" >
        <input id="taskInput" placeholder="enter task" >
        <button id="addBtn">Add Task</button>
        <div class="items"></div>
    </div>
    <script src="./index.js"></script>
</body>
</html>
const data = [];

const list = document.createDocumentFragment();

const nameEl = document.getElementById("name");
const jobEl = document.getElementById("job");
const task = document.getElementById("task");
const itemsEl = document.getElementById("items")
const addBtn = document.getElementById("addBtn");
const deleteBtn = document.getElementById("deleteBtn");

function addItem(){
    const name = document.getElementById("nameInput").value;
    const job = document.getElementById("jobInput").value;
    const task = document.getElementById("taskInput").value;
    data.push({ name, job, task });
    displayData(data)
}

function displayData(data){
    console.log(data)
    data.map(({ name, job, task }) => {
        const item = `
        <h1 id="name" class="name">${name}</h1>
        <h3 id="job" class="job">${job}</h3>
        <h4 id="task" class="task">${task}</h4>
        <button id="deleteBtn">Delete Task</button>
        `
        const items = document.createElement("div");
        items.innerHTML = item;

        list.appendChild(items)
    })
    itemsEl.appendChild(list)
}

addBtn.addEventListener("click", () => {
    addItem()
})


I have tried looping over the array of object but i am getting undefined.

Upvotes: 0

Views: 589

Answers (1)

Yip
Yip

Reputation: 63

You tried to select the 'items' div with:

const itemsEl = document.getElementById("items")

But you div doesn't have an id. You could add an id or you could:

const itemsEl = document.getElementsByClassName("items")[0]

Upvotes: 1

Related Questions