I have a button and empty div in HTML.
<button id="add_sentence">Click here!</button>
<div id="parent"></div>
In JS, I have data in array
let data = [{ sentence: "Hi, I'm from Azerbaijan" }, {sentence: "I'm 36 years old"}, { sentence: "I learn front-end development}]
I need a function that when I click on button ("#add_sentence"), it takes only one sentence from array ("data") and adds to div ("#parent").
I can add all array to empty div with 1 click. But I want 1st click adds 1st sentence. Then, 2nd click adds 2nd sentence. 3rd click adds 3rd sentence and so on.
Can anyone help?
let data = [{ sentence: "Hi, I'm from Azerbaijan" }, {sentence: "I'm 36 years old"}, { sentence: "I learn fron-end development"}];
const button = document.querySelector("#add_sentence");
const parent = document.querySelector("#parent");
let clickCount = 0;
button.addEventListener('click', () => {
if (clickCount < data.length) {
const nextSentence = document.createElement('p');
nextSentence.innerText = data[clickCount].sentence;
parent.appendChild(nextSentence);
clickCount++;
}
})
<button id="add_sentence">Click here!</button>
<div id="parent"></div>