i have for example:
<span id="name1">name1</span>
<span id="name2">name2</span>
<span id="name3">name3</span>
<span id="name4">name4</span>
<span id="name5">name5</span>
i must use:
$("#name1").click(function(){
$(this).css('background-color', 'red');
});
$("#name2").click(function(){
$(this).css('background-color', 'red');
});
etc
i would like somethings:
$("#name [1-5] ").click(function(){
$(this).css('background-color', 'red');
});
i dont will add class. i would like make this for id and regular expression.
You have a few options:
Use a class. It’s easy to add, and is exactly the right use for them in this instance. It will also be fastest.
Use a loop:
for(var i = 1; i <= 5; i++) {
$(“#name” + i).click(function(){
$(this).css(‘background-color’, ‘red’);
});
}
Use attribute selectors:
$('span[id^="name"]')That will grab all spans with an id that starts with “name”. Just know, this is the slowest option, so I would avoid it if you can.