0

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()
    
    }
5
  • 4
    It would be p[i].remove() in the case of a for..loop Commented Jul 3, 2021 at 11:11
  • 1
    you mean ps[i].remove() , yeah, it worked :) thanks! would you care to explain why inside the forEach, it works with p.remove() ? is it because p is the argument passed inside function(p) ? Commented Jul 3, 2021 at 11:16
  • 1
    p is not even defined in your second code. You could use it in your first code because it is a param in your forEach callback. You can do ps[i]. Commented Jul 3, 2021 at 11:17
  • 1
    ps is a NodeList - therefore ps[i] Commented Jul 3, 2021 at 11:19
  • clear now. Thanks again! Commented Jul 3, 2021 at 11:19

1 Answer 1

1

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>

Sign up to request clarification or add additional context in comments.

5 Comments

hey, thanks! that goes even a bit further :)
@notADevYet it does not, it just uses a setTimeout (for demo purpose) over your coding typo.
I was meaning more like the full and detailed explanation you gave me ;)
@notADevYet Please accept the answer if it is what you want...
@decpk I just did it. Sorry, i still need to learn better how this forum works.

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.