简体   繁体   English

如何选择具有相同类名的 javaScript 中的所有类?

[英]How can I select the all classes in javaScript with same classname?

Can you please help me with this to solve out?你能帮我解决这个问题吗? the bg-color with the 1st div is only changing but the rest is not working help me to solve this!第一个 div 的 bg-color 只是在改变,但其余的不起作用帮助我解决这个问题!

 const hexNum = [0,1,2,3,4,5,6,7,8,'A','B','C','D','E','F']; const hexBtn = document.querySelector('.btn-hex'); const bgPale = document.querySelector('.bg-color'); const hexCode = document.querySelector('.color-code'); hexBtn.addEventListener('click', getNewHex); function getNewHex(){ let newHexCode = '#'; for (let i = 0; i<6; i++){ let randomHex = Math.floor(Math.random()*hexNum.length); newHexCode +=hexNum[randomHex]; //console.log(newHexCode); } bgPale.style.backgroundColor = newHexCode; hexCode.innerHTML = newHexCode }
 <div class="bg-color palette-1"></div> <div class="bg-color palette-2"></div> <div class="bg-color palette-3"></div>

The issue here is that you are using document.querySelector('.bg-color') which returns the first Element within the document that matches the specified selector, or group of selectors.这里的问题是您正在使用document.querySelector('.bg-color')它返回文档中与指定选择器或选择器组匹配的第一个元素。 You need to actually use here document.querySelectorAll('.bg-color') instead as it returns a NodeList representing a list of the document's elements that match the specified group of selectors.您需要在此处实际使用document.querySelectorAll('.bg-color')因为它返回一个 NodeList 表示与指定选择器组匹配的文档元素列表。 Then you will also need to loop through each of the node to change the style like:然后您还需要遍历每个节点以更改样式,例如:

const bgPale = document.querySelectorAll('.bg-color')
bgPale.forEach(el => el.style.backgroundColor = newHexCode);

For more info:欲了解更多信息:

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何对 JavaScript 中具有相同类名的表中的所有列求和? - How do I sum all columns in a table with the same classname in JavaScript? Javascript:按类别名称选中所有复选框 - Javascript: Select all checkboxes by classname 我将如何选择所有具有相同名称的div类,但使用jQuery / javascript的当前div除外? - How would I select all div classes with the same name except the one in the current div with jquery/javascript? 如何从 Vanilla Javascript 中的多个类中获取正确的类名 - How can i get correct className from multiple classes in Vanilla Javascript javascript 如何在选择选项中从相同的类名中收集值? - How can javascript collect values from the same classname in select-option? 如何在具有相同类名的所有元素上调用javascript函数 - How to call javascript function on all elements with the same classname 如何使用 JavaScript 选择特定的 className - How to select specific className with JavaScript 选择具有相同类名的所有父项 - Select all parents which has same classname 如果我有多个 ul 并且所有 li 具有相同的类名,我如何获得特定于 ul 的 li - how can I get the the li specific to a ul if i have more than one ul and all the li have same classname 如何使用 jQuery/JavaScript 删除所有 CSS 类? - How can I remove all CSS classes using jQuery/JavaScript?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM