I'd like to extend jQuery selection so that it treats a given selection value as an ID.
For example, when you do $("foo.bar") , jQuery will try to select all elements with the tag name foo and the class bar, but I want jQuery to select the element with an ID of foo.bar. Instead of having to escape dots and prepend a # each time, I'd like to add to jQuery as a function so that I can do something like $("id:foo.bar").
Is this possible with jQuery? If so, can anyone show me some examples?
Thanks.
It is. You can create you own selectors by extending .expr[]. Example:
$.extend($.expr[':'], {
'id': function(elem, i, attr){
return( elem.id === attr[3] );
}
});
Usage would be:
$(':id(foo.bar)');
Demo: http://www.jsfiddle.net/cwwGk/1/
If you replace ID selection with an attribute filter, it will have to test every element on the page for that ID instead of using document.getElementById.
If you want a little more convenience, just create your own wrapper. you can use jQuery's namespace if you want:
jQuery.byId = function(id){return $(document.getElementById(id));};
$.byId('foo.bar').addClass('something');
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With