Search code examples
javascriptdomhtmlcollection

Removing element by outerHTML from html collection


I have the following code. I am trying to make an element removed by setting outerHTML to empty(''). I also made few research on html collections and found that it is a live collection

ref :

So all I know is if I change document then the list should change. The code proves this behavior and the loop runs for 4 times despite my initial html collection being of length 9. Now when I replace the outerHTML with innerHTML then the loop for 9 times. So if the list should update with the document being changed, why does not this happen when I replace outerHTML with innerHTML

function expTble() {


    let tables = document.getElementsByTagName("table")

    let captions = document.getElementsByTagName("caption")


    if (captions.length > 1) {
        
        console.log(`${tables.length} tables ${captions.length} captions`)

        for (let i = 0; i < captions.length; i++) {

            console.log('index : ' + i)
         
            captions[i].outerHTML = ''

        }

        return

    }

    for (let i = 0; i < tables.length; i++) {
        // Do stuffs
        TableExport(tables[i], { bootstrap: false })
    }



}

Here is my result

When using outerHTML

9 tables 9 captions 
index : 0 
index : 1 
index : 2 
index : 3 
index : 4

When using innerHTML

9 tables 9 captions 
index : 0 
index : 1 
index : 2 
index : 3 
index : 4 
index : 5 
index : 6 
index : 7 
index : 8

Solution

  • The live collection updates itself when the element reference by it is changed. In your case the outerHTML changes the element and this updates the collection. But the innerHTML is a deferent piece. It is not something that is referenced by the collection so changes to the child element does not update the html collections.

    if you want to remove the element using the same logic, Use While loop and check , if the length is 0, and ref the removing element by 0th index.

     if (captions.length > 1) {
    
            while (captions.length > 0) {
                captions[0].outerHTML = ''
            }
    
            return
    
        }