I'm trying to allow users to change the main color ( .primary-color
) of my page, choosing between preset colors.
I found this little snippet
function change(i) {
var color = document.getElementById("color");
color.style.backgroundColor = i;
}
.div-1 {
background-color: orange;
width: 50px;
height: 50px;
float: left;
margin: 5px
}
.div-2 {
background-color: black;
width: 50px;
height: 50px;
float: left;
margin: 5px
}
.div-3 {
background-color: green;
width: 50px;
height: 50px;
float: left;
margin: 5px
}
.div-4 {
background-color: red;
width: 50px;
height: 50px;
float: left;
margin: 5px
}
#color {
background-color: transparent;
border: 2px solid #000;
width: 50px;
height: 50px;
float: left;
margin: 5px;
}
<div class="div-1" onclick="change('orange')"></div>
<div class="div-2" onclick="change('black')"></div>
<div class="div-3" onclick="change('green')"></div>
<div class="div-4" onclick="change('red')"></div>
<div id="color"></div>
There are 4 colors to choose from to apply to the fifth DIV. It works well.
But if I want to change the fifth DIV, i.e. pass the ID to a class, it doesn't work for me:
function change(i) {
var color = document.getElementsByClassName("color");
color.style.backgroundColor = i;
}
.div-1 {
background-color: orange;
width: 50px;
height: 50px;
float: left;
margin: 5px
}
.div-2 {
background-color: black;
width: 50px;
height: 50px;
float: left;
margin: 5px
}
.div-3 {
background-color: green;
width: 50px;
height: 50px;
float: left;
margin: 5px
}
.div-4 {
background-color: red;
width: 50px;
height: 50px;
float: left;
margin: 5px
}
.color {
background-color: transparent;
border: 2px solid #000;
width: 50px;
height: 50px;
float: left;
margin: 5px;
}
<div class="div-1" onclick="change('orange')"></div>
<div class="div-2" onclick="change('black')"></div>
<div class="div-3" onclick="change('green')"></div>
<div class="div-4" onclick="change('red')"></div>
<div class="color"></div>
Here on the site there is a similar topic but it was not entirely clear to me: What is the difference between selecting by ID or ClassName?
I don't know much about JS, could it be a typo? Thank you very much in advance
When you take the name of the class, it takes an array so you have to go through the elements to be able to change their style.
The difference lies in what each method returns:
by id
The id, considering that it must be a unique key, would return a single element, the one with the color value as the id attribute .
Per class
The class, being a key that can occur in multiple elements of your DOM , returns a collection of all the elements that have said class. Therefore, to be able to refer to
<div id="color"></div>
you should do:With this you would access the first element that appears in the DOM of your page and that has the class "color". In your case, having only one would be referencing it correctly.
EDIT
I add snipped for clarity and adding to my solution the one proposed by @Iñigo Irigoyen Erquicia: