gpt4 book ai didi

javascript - 仅使用 javascript 查找 sibling 并添加类

转载 作者:行者123 更新时间:2023-11-28 00:43:02 27 4
gpt4 key购买 nike

我想在 javascript 中的目标元素的兄弟元素上添加类。我在使用 jquery 之前已经这样做过,这非常简单。但在我目前的组织中,他们不使用 jquery,我需要使用 javascript,这对我来说非常困难。

我已经编写了一些代码,将点击功能附加到匹配的元素,但之后我没有获得任何登录信息来了解如何实现它。 fiddle

var elements= document.getElementsByTagName('*'),i;
i=0;

while(elements[i]){
if(elements[i].className=='c'){
elements[i].addEventListener('click',function(){
this.jsSiblings().jsAddClass('newClass')
})
}
i++
}


Array.prototype.jsSiblings= function(){

//code
}

Array.prototype.jsAddClass=function(){

//code
}

最佳答案

你可以使用 JS 中的基函数来添加一个类, element.classList.add("anotherclass"); (来自 MDN )在这里你会发现关于没有 jQuery 的 sibling : How to find all Siblings of currently selected object

关于javascript - 仅使用 javascript 查找 sibling 并添加类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27733933/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com