簡體   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?

我正在使用 document.querySelector,我需要它來 select 所有包含 class “測試”的 div。 到目前為止,querySelector 僅成功選擇了第一個 div。

我如何用我目前的 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"); }

任何幫助都將不勝感激。 謝謝

使用document.querySelectorAll('.test'); 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>

不推薦,但嘗試document.getElementsByClassName("test")

您可以嘗試使用 jquery

$(".test .card-decorator-stroke").addClass("brand-curve-stroke").removeClass("card-decorator-stroke");

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM