Get element ID in jQuery
February 1st, 2009 currentlyOfflineA very small tip for people who are new with jQuery.
let’s say you have a list of images, with the same class, something like:
1:<img src="somethinghere1" alt="alt1" title="title1" class="someClass" />
2:<img src="somethinghere2" alt="alt2" title="title2" class="someClass" />
3:<img src="somethinghere3" alt="alt3" title="title3" class="someClass" />
4:<img src="somethinghere4" alt="alt4" title="title4" class="someClass" />
I’m not going into more detail on this straightforward code. If you’re unsure why I’m using both title and alt on image, feel free to ask any SEO person
So, anyway, you want some action when user moves mouse over each image. Let’s say you want to add 75 pixels of solid pink border around the image(hope you’re not…). I know you expect something very simple like this.css(“border”, “75px solid pink”). Unfortunately that won’t work for you
But there’s a quite simple solution if you know that you can get id of current element and it’s stored in this.id
So add id’s to your elements:
1:<img src="somethinghere1" id="img1" alt="alt1" title="title1" class="someClass" />
2:<img src="somethinghere2" id="img2" alt="alt2" title="title2" class="someClass" />
3:<img src="somethinghere3" id="img3" alt="alt3" title="title3" class="someClass" />
4:<img src="somethinghere4" id="img4" alt="alt4" title="title4" class="someClass" />
And now it’s easy:
1:$(".someClass").mouseover(function(){
2: $("#" + this.id).css("border","75px solid pink");
3:});
Here we are – you solved this annoying problem, so you can switch you computer off, call you best mates and go for a beer. Computers are bad for you!