1
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 ??

2 Answers 2

1

Your this code needs to be changed to

newText.innerText = `${array[0].text}`;
Sign up to request clarification or add additional context in comments.

2 Comments

Hey i haven't why will i do that
what do you mean bro? I do not understand, sorry I just new joined this site xD ..
0
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,
}

3 Comments

thank you so much, it work ... is the array writing wrong?
oo i see xD .. thnk you one more time for the insight
ohh, I understand now, thank you so much, I learned a lot here

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.