Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery custom selection

Tags:

jquery

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.

like image 397
Tom Tucker Avatar asked Nov 18 '25 00:11

Tom Tucker


2 Answers

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/

like image 141
jAndy Avatar answered Nov 20 '25 14:11

jAndy


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');
like image 25
RightSaidFred Avatar answered Nov 20 '25 15:11

RightSaidFred



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!