I'm trying to create simple selection option for users when selecting a particular font style. If they click on a font div
, the background of that div
should change color.
The problem I'm having is that the first font div
works perfectly in changing color - however the other font div
s do not follow suit.
HTML
<div class="fonts">
<div id="font" class="minecraft-evenings">
Hello
<p>Minecraft Evenings</p>
</div>
<div id="font" class="minecrafter">
Hello
<p>Minecrafter 3</p>
</div>
<div id="font" class="volter">
Hello
<p>Volter</p>
</div>
</div>
JavaScript/JQuery
$(document).ready(function() {
$('#font').click(function() {
$(this).css("background-color", "#000");
$('#font').not(this).css("background-color", "#f1f1f1");
});
});
The problem:
ID's are meant to be unique identifiers. You should be using classes if you want to identify multiple elements. For this reason, when you select by ID with
$("#font")
, jQuery (which uses native javascript'sgetElementById
) will only return the first element it comes across that has that ID. This is because if the DOM is valid, it shouldn't find anymore instances of that ID and it would be a waste of processing to continue looking.A solution:
Remove the
font
ID's from yourdiv
s and replace them with a class instead, likeclass="font"
. Since you already have some classes identified, you can use multiple classes separated by spaces, like:class="font minecrafter"
. After doing this, you will be able to select your elements with thefont
class using this selector:$(".font")