How can i run all these paragraph?
<p>Player 1: Test 1</p>
<p>Player 2: Test 2</p>
const para = document.querySelector('p');
para.addEventListener('click', updateName);
function updateName() {
let name = prompt('ENter your name');
para.textContent = 'Player 1:' + name;
}
i know querySelector returns the first element but i want to know how can i return both paragraph. I already tried using querySelectorAll but i do not know how to write it. Sorry iam still learning btw
Advertisement
Answer
I guess this is what are you looking for:
const paragraphs = Array.from(document.querySelectorAll('p'));
for (let index in paragraphs) {
paragraphs[index].addEventListener('click', () => {
const name = prompt('Enter your name:');
paragraphs[index].textContent = `Player ${+index + 1}: ${name}`;
});
}<p>Player 1: Test 1</p> <p>Player 2: Test 2</p>