可以在JavaScript中更改其名称的访问元素可以
我想将元素类的类别从 score -box1 更改为 score -box1. -Active 。我创建了一个const $ target,以尝试访问类得分-box1,但它不起作用。
const $target = document.getElementByClassname('score -box1')
function PlayerScore(score = 0){
if(score == 1){
$target.toggle('-active');
}else if(score == 2){
$target.toggle('-active');
}else if(score == 3){
$target.toggle('-active');
}
return( /*html*/
`
<div class = "container">
<div class = "score -box1">one</div>
<div class = "score -box2">two</div>
<div class = "score -box3">three</div>
</div>
`
)
}
I'd like to change an element's class from score -box1 to score -box1.-active. I created a const $target to try to access the class score -box1 but its not working.
const $target = document.getElementByClassname('score -box1')
function PlayerScore(score = 0){
if(score == 1){
$target.toggle('-active');
}else if(score == 2){
$target.toggle('-active');
}else if(score == 3){
$target.toggle('-active');
}
return( /*html*/
`
<div class = "container">
<div class = "score -box1">one</div>
<div class = "score -box2">two</div>
<div class = "score -box3">three</div>
</div>
`
)
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
正确的方法是
.querySelectorall
,并且它返回节点列表,如果您在下面的末尾添加[0]
,您将获得该节点列表的第一个元素(也许您现在想要的),但是,如果您想要所有目标元素使用for loop
通过document.queryselectorall('scorce -box1')循环循环。
或者,您可以用
.querySelectorAll
使用.querySelector
,它将自动删除第一个元素: https://www.w3schools.com/jsref/met_document_queryselector.aspThe proper method is
.querySelectorAll
and it returns a node list , if you add a[0]
at the end like below, you will get the first element of that node list (which maybe what you want for now), but if you want all target elements use afor loop
to loop overdocument.querySelectorAll('score -box1')
array.Or you can replace the
.querySelectorAll
with with.querySelector
, it will automatically rturn the first element: https://www.w3schools.com/jsref/met_document_queryselector.asp