I have a piece of code that, while it works perfectly elsewhere, is not working when I try to apply it to a child element. I am trying to simply replace a class in the classList
for an i
element when the addEventListener("mouseover"
for the parent tag is triggered. Here’s my code:
document.getElementById("parentTag").addEventListener("mouseover", function() { var elem = document.getElementById("parentTag").getElementsByTagName("i")[0]; elem.classList.replace = ("fal", "fas"); });
This should be pretty straight forward but, for some reason that I cannot determine, it is not working here. I can do other things with this element (e.g. change style
attributes, etc.) but anything involving classList
(replace
, add
, remove
) is completely failing. I can however call the classList
into the console with console.log(elem.classList.value);
but I can’t change it.
Does anyone know how to fix this or what I might be doing wrong?
NOTE: Sorry if the question was a little unclear, I don’t know how to better describe it outright. If you need clarification please let me know.
Advertisement
Answer
You accidentally used an assignment operator for classList.replace()
. It should be elem.classList.replace("fal", "fas")
.
document.getElementById("parentTag").addEventListener("mouseover", function() { var elem = document.getElementById("parentTag").getElementsByTagName("i")[0]; elem.classList.replace("fal", "fas"); });