Hi. After getting my feet wet with jQuery via a beginner’s book and some tutorial videos I am setting up a page to play around with various animation methods and I am running into a problem applying a function to multiple elements with the same ID at once.
HTML
<div id="playground">
<div id="sandbox">
<div id="toy">Lorem Ipsum</div>
</div>
<div id="sandbox">
<div id="toy">Lorem Ipsum</div>
</div>
<div id="sandbox">
<div id="toy">Lorem Ipsum</div>
</div>
</div>
<div id="control">
<button class="reset">Reset</button>
<button class="fontsize">Increase Font</button>
</div>
CSS
#playground {
width: 900px;
margin: 20px auto;
}
#sandbox {
float: left;
width: 300px;
height: 400px;
}
#toy, #toy1, #toy2, #toy3 {
width: 50px;
height: 50px;
padding: 5px;
position: relative;
background-color: #96ac1c;
text-align: center;
font-size: 12px;
color: #ffffff;
}
jQuery
(function() {
// font size
$('button.fontsize').click(function(){
$('#toy').css('font-size','16px');
});
})();
This only changed the font size for the first #toy div (no console errors). I went back to another tutorial that marked up various <span> elements across multiple <p> elements as well as some Google searching to get some guidance.
(function() {
// font size
$('button.fontsize').click(function(){
$('#playground').find('#toy').each(function() {
$('#toy').css('font-size','16px');
});
});
})();
or
(function() {
// font size
$('button.fontsize').click(function(){
$.each($('#toy'), function() {
$(this).css('font-size','16px');
});
});
})();
Same result on both, only the first #toy div changes. I can get it to work by renaming each div and chaining $(‘#toy1,#toy2,#toy3’), but that doesn’t seem very practical or flexible. How can I get this to work with using chaining?