[英]How do I replace a class for a child element?
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:当父标签的addEventListener("mouseover"
被触发时,我试图简单地将 classList 中的classList
替换为i
元素。这是我的代码:
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 (eg change style
attributes, etc.) but anything involving classList
( replace
, add
, remove
) is completely failing.我可以用这个元素做其他事情(例如更改style
属性等),但任何涉及classList
( replace
、 add
、 remove
)的事情都完全失败了。 I can however call the classList
into the console with console.log(elem.classList.value);
但是,我可以使用console.log(elem.classList.value);
将classList
调用到控制台中; 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.如果您需要澄清,请告诉我。
You accidentally used an assignment operator for classList.replace()
.您不小心为classList.replace()
使用了赋值运算符。 It should be elem.classList.replace("fal", "fas")
.它应该是elem.classList.replace("fal", "fas")
。
document.getElementById("parentTag").addEventListener("mouseover", function() {
var elem = document.getElementById("parentTag").getElementsByTagName("i")[0];
elem.classList.replace("fal", "fas");
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.