How do you apply some script to each css element with the same id?
HTML:
<div id="tab">This is a paragraph.</div> <div id="tab">This is a paragraph.</div> <div id="tab">This is a paragraph.</div> <div id="tab">This is a paragraph.</div> CSS:
#tab{ height:30px; width:130px; background-color:red; } JQuery:
$(document).ready(function() { function randomNumber() { return Math.floor(Math.random() * 255) } $('#tab').mouseover(function() { $('#tab').css('background-color', 'rgb(' + randomNumber() + ',' + randomNumber() + ',' + randomNumber() + ')'); }); $('#tab').mouseout(function() { $('#tab').css('background-color', 'white'); }); }); I have this fiddle and I want the color change to affect ALL #tabs, and not just the first one, how to do this?
Fiddle can be found here.
+4
5 answers
You can assign an identifier only once! Change it to classes like http://jsfiddle.net/nHCXV/3/
+2
Instead of giving the same id , you can declare a div without any id or class and specify the code below. To learn more about selectors, go to this link .
$(document).ready(function() { function randomNumber() { return Math.floor(Math.random() * 255) } $('div').mouseover(function() { $('div').css('background-color', 'rgb(' + randomNumber() + ',' + randomNumber() + ',' + randomNumber() + ')'); }); $('div').mouseout(function() { $('div').css('background-color', 'white'); }); });โ or just use class instead of id . Because identifiers are unique but not classes .
0