1

I get the error Uncaught TypeError: element.remove is not a function when I try to remove multiple elements. My code is:

function removeElements(value, selector) {
  if(value === undefined || selector === undefined) {
    return undefined;
  }
  
  if(value !== true) {
    return false;
  }
  
  const element = document.getElementsByTagName(selector)
  element.remove();
}

I don't get the error if I replace document.getElementsByTagName(selector) with document.getElementById(selector). How do I fix this?
Update
I put @wxker's code snippet in a loop to remove all elements. Here is the final working code:

function removeElements(value, selector) {
    if(value === undefined || selector === undefined || value !== true) {
        return undefined;
    }
    
    for (const element of document.getElementsByTagName(selector)) {
      element.remove();
    }
    
    console.log(`All ${selector} elements removed.`);
}
Invalid Name
  • 38
  • 3
  • 7

1 Answers1

3

document.getElementsByTagName returns an array-like HTMLCollection of elements while document.getElementById returns just one element. This is because there can be multiple elements with the same tag.

var myobjArr = document.getElementsByTagName(selector);
myobjArr[0].remove();

The above code snippet will work, but you'll have to manage the index of the array to remove the right element.

connexo
  • 53,704
  • 14
  • 91
  • 128
wxker
  • 1,841
  • 1
  • 6
  • 16