Useful Tips
Sometimes is really useful not only to read the docs, but to be aware of what the community is writing. Although you get familiar with a library or framework, it happens sometimes to discover very very useful things in them, kind of snippets, that you’ve missed all the time.
In that sense, I’m going to talk about something really small as code in jQuery, but that is quite used. The id selector.
It just so happens that after you discover the selection of an attribute with .attr() method you start selecting even the ids with it.
$('element').attr('id'); |
Which of course works quite well, but there is a built-in method that has clearer syntax and … better performance – the id.
Think of something like that:
$('element').click(function() { alert($(this).attr('id')); } |
It can be replaced with:
$('element').click(function() { alert($(this).id); } |
It’s cool!
You are still overthinking the problem. No need to wrap in jquery at all, you can get the id like this:
$(‘element’).click(function() {
alert(this.id);
}
Have a look at
http://www.w3schools.com/jsref/dom_obj_all.asp
of course, if you dont have the raw node, your technique is good, eg:
$(‘ul li:first’).id;
Though you can also access the raw node;
$(‘ul li’)[0].id;
This is actually how we got the ids of elements way back when before the days of jQuery, when people actually had to know javascript!
Just to reply to all comments, of course I know there’s a “pure” javascript approach and naturally the jQuery’s solution derive from that. Actually if you’d like to access an attribute for a particular element you can use the same notation:
var element = document.getElementById(‘element_id’);
alert(element.id);
What jQuery is doing is practically the same, while I was trying the show that sometimes we make it the hard way with $(element).attr() method, which is slow and the notation is not so elegant.
The same happens when you try to access the title, src or whatever attribute you’d like.
best regards,
stoimen
It’s not work in 1.4.2:
$(function(){
alert( $(“#zz”).id);
});
ajsiojqijowis
result is ‘undefined’.
Hi, usually i use $(selector).attr(‘id’); with jquery …
nice tip 🙂
how can i get id of all same class element ?
// this also working ……
// no need to write ready method.
// no need to write ready method
sorry .. i can’t submit my full code
Thank you man!!! You made my day
$(‘element’).click(function() {
alert($(this).attr(‘id’));
}
above code not workin.
pls help how to get current element value.