If I understand your problem, you need to recursively check child nodes for elements with this class.
function findShallowest( root, sel ) { var children = root.children(); if( children.length ) { var matching = children.filter( sel ); if( matching.length ) { return matching.first(); } else { return findShallowest( children, sel ); } } else { return null; } } var selected = $('.selected'); findShallowest( selected, ':text' );
Example: http://jsfiddle.net/Qf2GM/
EDIT: Forgot the return statement and had an identifier selector instead of a class selector for the initial .selected .
Or do it in your own plugin:
Example: http://jsfiddle.net/qX94u/
(function($) { $.fn.findShallowest = function( sel) { return findShallowest( this, sel ); }; function findShallowest(root, sel) { var children = root.children(); if (children.length) { var matching = children.filter(sel); if (matching.length) { return matching.first(); } else { return findShallowest(children, sel); } } else { return $(); } } })(jQuery); var result = $('.selected').findShallowest( ':text' ); alert( result.val() );
user113716
source share