Want to extend jQuery to select by name attribute more elegantly

I find this selector format cumbersome if I need to use it often:

$('[name="someElementName"]').val()

I thought about extending jQuery so that I can use a format like this:

$('@someElementName').val()

I understand that jQuery is just following the convention of CSS and that I am breaking convention.

Regarding the choice of "@", I just picked a special character that seemed unused for selectors and not likely to create a conflict. If anyone has a better suggestion I'm open to suggestions.

I don't have the option to not use the name attribute as part of the selector.

I was thinking about using regular expression like this:

selectorString.replace(/\@([\d\w\s\-]*)/g, '[name="$1"]')

From here I am stuck as how to extend jQuery to utilize that regex in such a way that I can use code like "$('@someElementName').val();

Answers


How about this:

(function($) {
    $.named = function(name, context) {
        context = context || document;
        return $(context.getElementsByName(name));
    }
})(jQuery);

usage:

$.named('foo').val();

See http://jsfiddle.net/alnitak/n6nEW/


Need Your Help

Trouble Creating Directories with mkdir

ruby mkdir

New to Ruby, probably something silly

Get text value from dynamically creating text boxes

c# asp.net findcontrol nested-controls

Given multiple dynamically created textboxes, I want to get the text filled by the user.

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.