[英]Javascript: querySelector only selects 1 div. How do I get it to select all divs with the same class?
I'm using document.querySelector and I need it to select all divs that contains the class "test".我正在使用 document.querySelector,我需要它来 select 所有包含 class “测试”的 div。 So far querySelector selects the first div only successfully.
到目前为止,querySelector 仅成功选择了第一个 div。
How do I do that with my current Javascript?我如何用我目前的 Javascript 做到这一点?
var removeCurveStroke = document.querySelector('.test'); if(document.querySelector('.test').classList.contains('card-decorator-stroke')){ removeCurveStroke.classList.remove("card-decorator-stroke"); removeCurveStroke.classList.add("brand-curve-stroke"); console.log("Test"); }
Any help is gladly appreciated.任何帮助都将不胜感激。 Thanks
谢谢
Use document.querySelectorAll('.test');
使用
document.querySelectorAll('.test');
Documetnation for querySelectorAll querySelectorAll 的文档化
document.querySelectorAll('.card-decorator-stroke').forEach(function(removeCurveStroke) { removeCurveStroke.classList.remove("card-decorator-stroke"); removeCurveStroke.classList.add("brand-curve-stroke"); });
.test{ height: 1rem; background: blue; }.card-decorator-stroke { background: red; }.brand-curve-stroke { background: green; }
<div class="test"></div> <div class="test card-decorator-stroke"></div>
not recommendable but try document.getElementsByClassName("test")
不推荐,但尝试
document.getElementsByClassName("test")
You can try with jquery您可以尝试使用 jquery
$(".test .card-decorator-stroke").addClass("brand-curve-stroke").removeClass("card-decorator-stroke");
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.