我试图在单击链接后用纯 JS 向 div 添加一个类(在本例中,链接的 ID #switchlogin
)。当我对我的元素进行 console.log 时,我可以单击该对象并看到它当前在其 classList
中有两个名称。然而,当我 console.log element.classList
时,我收到一个“undefined”。我不确定为什么我会收到未定义的消息,以及为什么我不能添加我的新类名。
问题在此处重现:https://jsfiddle.net/swf5zc74/
这是我的 HTML 的一部分:
<div class="sign_in modal">
<h1>Get Started!</h1>
<form action="" method="get">
<input type="text" name="fname" placeholder="Name" required>
<input type="text" name="email" placeholder="Email" required>
<input type="password" name="password" placeholder="Password" required>
<input type="submit" value="Submit" class="submit">
</form>
<h3><a href="#" id="switchLogin">Been Here Before?</a></h3>
</div>
我的JS:
var body = document.getElementsByTagName('body'),
signIn = document.getElementsByClassName('sign_in modal'),
logIn = document.getElementsByClassName('log_in'),
switchLogIn = document.getElementById('switchLogin'),
switchSignIn = document.getElementById('switchSignin'),
link = document.querySelector('a');
link.addEventListener("click", function(e){
if ((e.target || e.srcElement).id == 'switchLogin'){
console.log(signIn);
console.log(signIn.classList);
signIn.classList += ' slideOut';
}else{
console.log("nope");
}
})
最佳答案
signIn
是 document.getElementsByClassName('sign_in modal')
的结果 - getElementsByClassName
返回一个集合 - 所以你必须引用你想要的索引:
console.log(signIn[0].classList);
关于javascript - el.classList 未定义,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33132393/