I am trying to create a card where all information are stored. However after I created the variable and tried to append text to it, I got an undefined error. What should I change?
Here’s the error:
Uncaught TypeError: title is undefined createCards http://localhost/Projects/diary/:86 createCards http://localhost/Projects/diary/:75 success http://localhost/Projects/diary/:103 jQuery 6 http://localhost/Projects/diary/:96 jQuery 13 diary:86:13 createCards http://localhost/Projects/diary/:86 forEach self-hosted:206 createCards http://localhost/Projects/diary/:75 success http://localhost/Projects/diary/:103 jQuery 6 http://localhost/Projects/diary/:96 jQuery 13
function cardClass(status) {
let defaultClass = ["card", "mb-3", "h-100", "text-center", "mw-25"]
switch (status) {
case 0:
return defaultClass.concat(["border-danger"]); break; // coming soon
case 1:
return defaultClass.concat(["border-warning"]); break; // developing
case 2:
return defaultClass.concat(["border-success"]); break; // success
case 3:
return defaultClass.concat(["border-info"]); break; // improving (beta)
case 4:
return defaultClass.concat(["border-danger"]); break; // testing
default:
return defaultClass.concat(["border-info"]); break; // unknown
}
}
function createCards(data) {
data.forEach(obj => {
const titleClass = ["card-header", "text-primary", "fw-bold"];
const card_class = cardClass(obj.status);
let col = document.createElement("div").classList.add("col");
let card = document.createElement("div").classList.add(...card_class);
let title = document.createElement("div").classList.add(...titleClass);
let body = document.createElement("div").classList.add("card-body");
let text = document.createElement("p").classList.add("card-text");
// Append text
title.innerText = obj.title; // This line is causing the error
// // Append elements
// body.appendChild(text); card.appendChild(title); card.appendChild(body)
// col.appendChild(card);
// document.getElementById("features").appendChild(col);
})
}
$("#features").ready(() => {
$.ajax({
type: "POST",
url: 'functions/getData.php',
data: { get: "features" },
success: function (data) {
checkJson = JSON.parse(data);
if (checkJson){
createCards(checkJson);
}
},
error: function (xhr, opt, err) {
console.warn(xhr, opt, err)
}
})
})
I’m sure I declared the variable but it is throwing an error. Any help is thanked in advanced!
Advertisement
Answer
document.createElement("div").classList.add("test") does not return your element, it returns the result of the add method, which is undefined.
You need something like this.
let title = document.createElement("div");
title.classList.add(...titleClass);
...
title.innerText = obj.title;
All your variables (col, card, title, body, text) are actually undefined at this point.