简体   繁体   English

Javascript:querySelector 只选择 1 个 div。 如何将其发送到 select 所有具有相同 class 的 div?

[英]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.

相关问题 如何让jQuery只修改一个div,而不是同一个类的所有div? - How do I make jQuery modify only one div, instead of all divs of the same class? 我在div里面有一个画布。 我怎么得到它? - I have a canvas inside the div. How do I get it? 如何在 JavaScript 中使用 querySelector 选择具有特定类的所有子元素,而不考虑它们在 HTML 中出现的顺序? - How can I select all child elements with a certain class using querySelector in JavaScript regardless of the order they appear in HTML? 如何使用 javascript 编辑具有相同 class 的所有 div 的 styles? - How do I edit the styles of all divs with the same class using javascript? 如何仅使用没有库的javascript从同一个类的不同div获取值的总和? - How can I get sum of values from different divs with the same class using only javascript without libraries? 如何选择具有相同类别的所有div - how to select all divs with the same class 我在div中动态创建一些文本区域。 如何在javascript中获取其名称? - I create dynamically some text area in a div. How can i get its names in javascript? 仅当滚动条位于div的底部时,才应进行滚动。 我如何实现此功能 - Scrolling should occur only when scroller is at the bottom of div. How do I achieve this functionality 获取每个div的所有选择值,其中多个div具有相同的类名 - Get all select values per div with multiple divs with same classname 如何通过querySelector更改具有相同class的多个div - how to change multiple divs with the same class through querySelector
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM