单击另一个元素后,使用vanilla javascript将类添加/删除到其他元素 [英] Use vanilla javascript to add / remove class to a different element after clicking on another one
问题描述
我查看了许多类似的问题,但找不到一个在vanilla JS中回答的具体示例如何将类添加到一个不同的元素中并从中删除。我知道它与设置循环和遍历元素有关,但我在确切的过程中迷路了。
I have looked through a number of similar questions but can not find a specific example of one that answers in vanilla JS how to add and remove a class to a different element from the one clicked on. I know it has something to do with setting up a loop and iterating through the elements, but I got lost in the exact process.
我有一些类名为 faq-container
的元素,当我点击它们中的任何一个时,我希望将类 faq-display
添加到body标签中。我知道我必须设置一个类似的循环(var i = 0; i< elements.length; i ++){elements [i] .classList.remove('hover');
但我不确定在代码中将其写入的确切位置以使其工作。我尝试了很多方法,但都失败了。
}
I have a number of elements with a class name of faq-container
and when I click on any of them, I would like the class faq-display
added to the body tag. I know I have to set up a loop like for (var i = 0; i < elements.length; i++) { elements[i].classList.remove('hover');
}
but I am unsure as to exactly where to write it in the code to make this work. I have tried a number of ways but all fail.
我当前的脚本如下,我只是定位数组中的第一个元素,但我希望能够点击任何 faq-container
元素并将类名添加到第一个也是唯一的body标记:
My current script is as follows, where I simply target the first element in the array, but I want to be able to click on any of the faq-container
elements and add the class name to the first and only body tag:
document.addEventListener("DOMContentLoaded", function() {
document.getElementsByClassName('faq-container')[0].addEventListener('click', function() {
var faqToggle = document.getElementsByTagName('body')[0];
if (faqToggle.classList.contains('faq-display')) {
faqToggle.classList.remove('faq-display');
// alert("remove faq display!");
} else {
faqToggle.classList.add('faq-display');
// alert("add faq display!");
}
});
});
<div class="faq-container cf" id="faq-container">
<h3 <?=ifxless::element( 'name')?>><?=ifxless::fill($this,'name');?> </h3>
<div class="faq-content">
<div class="h_line"> </div>
<div class="faq-bullets" <?=ifxless::element( 'content')?>>
<?=ifxless::fill($this, 'content');?>
</div>
</div>
</div>
推荐答案
document.addEventListener("DOMContentLoaded", function() {
var faqContainers = document.getElementsByClassName('faq-container');
var faqToggle = document.getElementsByTagName('body')[0];
for (var i = 0; i < faqContainers.length; i++) {
faqContainers[i].addEventListener('click', function() {
if (faqToggle.classList.contains('faq-display')) {
faqToggle.classList.remove('faq-display');
// alert("remove faq display!");
} else {
faqToggle.classList.add('faq-display');
// alert("add faq display!");
}
});
}
});
这篇关于单击另一个元素后,使用vanilla javascript将类添加/删除到其他元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!