Reputation: 11
const array = [
{
text: "hello",
number: 23,
},
];
const container = document.querySelector(".container");
const btn = document.querySelector(".btn");
btn.addEventListener("click", createText);
function createText() {
const newText = document.createElement("h1");
newText.innerText = `${array.text}`;
container.appendChild(newText);
}
i want to get value text from array? what is wrong? why i get undefined ??
Upvotes: 1
Views: 56
Reputation: 2137
array[0].text
But you should change the structure of "array"... For the moment you have an array with only one element, and it's an object.
Either you want to handle an array of objects, or you want to only have one element, in that case you use an object:
const case1 = [
{
text: "hello",
number: 23,
},
{
text: "hello2",
number: 2345,
}
];
const case2 = {
text: "hello",
number: 23,
}
Upvotes: 0
Reputation: 954
Your this code needs to be changed to
newText.innerText = `${array[0].text}`;
Upvotes: 1