Search code examples
javascriptqueryselector

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!

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>


Solution

  • 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. 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. 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: