Skip to content

Instantly share code, notes, and snippets.

@cowboy
Created November 18, 2010 20:24
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save cowboy/705550 to your computer and use it in GitHub Desktop.
Save cowboy/705550 to your computer and use it in GitHub Desktop.
jQuery nodetype filter: Filter the selected elements by nodeType
/*!
* jQuery nodetype filter - v0.1pre - 11/18/2010
* http://benalman.com/
*
* Copyright (c) 2010 "Cowboy" Ben Alman
* Dual licensed under the MIT and GPL licenses.
* http://benalman.com/about/license/
*/
(function($){
var types = {
element: 1,
text: 3,
comment: 8,
document: 9
};
$.fn.nodetype = function( type ) {
var type = typeof type === "string" ? types[ type.toLowerCase() ] : type;
return this.pushStack( this.filter(function(){
return this.nodeType === type;
}), "nodetype", type );
};
})(jQuery);
@gnarf
Copy link

gnarf commented Jun 1, 2011

Out of random curiosity, why not something like this too?

$.expr.filters.nodetype = function ( elem, i, match ) {
    var type = types[ match[3].toLowerCase() ] || parseInt( match[3], 10 );

    return elem.nodeType === type;
}

@cowboy
Copy link
Author

cowboy commented Jun 1, 2011

+1

@gnarf
Copy link

gnarf commented Jun 1, 2011

Actually nevermind that previous idea... it seems the expr.filters implies the nodeType === 1 anyway... How lame...

@cowboy
Copy link
Author

cowboy commented Jun 1, 2011

Oh yeah, right... I remember having a big discussion in #jquery-dev about how the implicit nodeType === 1 really limits jQuery custom selectors :/

@donnielrt
Copy link

hey @cowboy, not sure if this code is relevant anymore, but out of curiosity, could you just pass types like Node.TEXT_NODE and Node.ELEMENT_NODE instead of using that artificial enumeration?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment