Skip to content Skip to sidebar Skip to footer

Error When I Am Trying To Remove An Element

In the following code i need to write the function of removing the element of the class (devil), i wrote the function for removing but something is wrong. Thank-you for your time!

Solution 1:

So do you have a method getElementByClass defined somewhere?

There is no getElementByClass in JavaScript, there is a document.getElementsByClassName which returns a collection.

var element = document.getElementsByClassName("devil")[0];
element.parentNode.removeChild(element)

Solution 2:

IDs are restricted to be unique in HTML (some web designers don't seem to think so. If you find one of them, punch them). Classes are not - and so any method finding a particular class tends to return a set of them.

If you expect to only have one of a particular HTML element, set its id instead of its class, and retrieve it with getElementById().

Conversely, if you expect to have multiple of a particular element type (ie, "borderBox" or "gameEnemy") use a class, and iterate through the results of getElementsByClassName using a for-loop, likely performing the same operation on each of them. (If you're not familiar with for loops, you may really want to go through a JavaScript basics course)


Post a Comment for "Error When I Am Trying To Remove An Element"