I am looking for a way to extract a part of an ID and use it in my script.
My HTML:
<div id="item1"></div>
<div id="item2"></div>
<div id="item3"></div>
<div id="item4"></div>
<div id="item5"></div>
My jQuery:
$('#item(1|2|3|4|5)').mouseout(function(event) {
//Get the number of the item (1,2,3,4,5)
item_number = ???
alert(item_number);
}
How can achieve this using jQuery?
I am looking for a way to extract a part of an ID and use it in my script.
My HTML:
<div id="item1"></div>
<div id="item2"></div>
<div id="item3"></div>
<div id="item4"></div>
<div id="item5"></div>
My jQuery:
$('#item(1|2|3|4|5)').mouseout(function(event) {
//Get the number of the item (1,2,3,4,5)
item_number = ???
alert(item_number);
}
How can achieve this using jQuery?
Share Improve this question asked Apr 16, 2013 at 22:32 Peter LurPeter Lur 7582 gold badges13 silver badges27 bronze badges 1-
4
Don't do that. Those items should be
<div class="item" data-id="1"></div> <div class="item" data-id="2"></div> ...etc...
– zzzzBov Commented Apr 16, 2013 at 22:35
3 Answers
Reset to default 5Additionally to what VisioN said. I would like to encourage you to use classes for this purpose:
<div class="item" id="item1"></div>
<div class="item" id="item2"></div>
<div class="item" id="item3"></div>
<div class="item" id="item4"></div>
<div class="item" id="item5"></div>
And
$(".item").mouseout(...)
You can use starts with selector:
$("[id^='item']").mouseout(function(e) {
var item_number = this.id.replace("item", "");
alert(item_number);
});
A simple way to do that is here:
$('div').mouseout(function() {
var this_id = $(this).attr('id');
alert(this_id);
});
If you want to make sure not all divs get alerted, give all of those divs a class and use this instead:
$('.myClass').mouseout(function() {
var this_id = $(this).attr('id');
alert(this_id);
});