On the page there are many blocks of the same type.
Example:

arr = document.body.getElementsByClassName('box') [<div class=​"box" style=​"background-color:​ rgb(122, 233, 132)​;​">​</div>​, <div class=​"box" style=​"background-color:​ rgb(133, 154, 188)​;​">​</div>​, <div class=​"box" style=​"background-color:​ rgb(59, 243, 75)​;​">​</div>​, <div class=​"box" style=​"background-color:​ rgb(175, 245, 235)​;​">​</div>​, <div class=​"box" style=​"background-color:​ rgb(56, 211, 118)​;​">​</div>​, ΠΈ Ρ‚.Π΄.] 

By the element of the array, we can get a certain block:

arr [i]

I'm wondering how to remove all these blocks from the markup gradually, starting with the last one? In general, how easy is it to remove a block by id?

    1 answer 1

    Using the selector :last-child you can get the last block with the class you selected. This is how it will look like a code:

     var lastBox = document.querySelector('.box:last-child'); 

    To consistently remove elements from the end of the array, you can use the following code:

     for (var i = (arr.length - 1); i >= 0; i--) { yourRemoveFunction(arr[i]); } 

    Using the selector :nth-child(n) you can get a block with the selected index. This is how it will look like a code:

     var selectedBox = document.querySelector('.box:nth-child(5)'); // 5-Ρ‹ΠΉ элСмСнт 
    • You can remove the last tag with this class as follows for (var i = (arr.length - 1); i >= 0; i--) { document.body.removeChild('.box:nth-child(i)') } - V. Rotenberh
    • @ V.Rotenberh, so you delete all the blocks, starting with the last - VenZell
    • thank. in essence, that was the task. - V. Rotenberh