Reputation: 327
I am practising with DOM manipulation, in this case with .remove(). I get to find all the 'p' in my HTML and remove them, with a forEach function.
const ps = document.querySelectorAll('p')
ps.forEach(function (p) {
p.remove()
})
But for the shake of learning, I would like to transform that forEach into a for Loop, but I am not sure how to fill in the function to make it work . I am trying :
const ps = document.querySelectorAll('p')
for (i = 0; i < ps.length; i++) {
p.remove()
}
Upvotes: 0
Views: 72
Reputation: 25408
You just have to use
ps[i].remove()
because ps
contains an array of all paragraph
. So you want to delete all elements. If you want to access the elements from the array one by one then you have to use index
(i.e. on which position they are in an array)
To simulate deletion after 2 second, I've used setTimeout
of 2s
With forEach
loop
const allP = document.querySelectorAll("p");
setTimeout(() => {
allP.forEach(p => p.remove())
}, 2000);
<p>1</p>
<p>2</p>
<p>3</p>
With for..loop
const allP = document.querySelectorAll("p");
setTimeout(() => {
for (let i = 0; i < allP.length; ++i) {
allP[i].remove();
}
}, 2000);
<p>1</p>
<p>2</p>
<p>3</p>
Upvotes: 1