JQuery: check if name attribute matches given string

Given the list of HTML inputs, text fields, and selections, I would like to check and see if there is a name attribute equal to the given string, and if necessary add a class to it.

For example:

if($('textarea, input, select').attr("name") == "this_name"){ $(this).addClass("myClass"); } 

I'm just not sure what I'm doing wrong here, but it doesn't seem to be working.

+8
jquery
source share
3 answers

try:

 $("textarea[name='this_name'], input[name='this_name'], select[name='this_name']").addClass("myClass"); 

Take a look at using CSS3 selectors in jQuery

+6
source share

What are you looking for:

 $('textarea, input, select').filter('[name="this_name"]').addClass("myClass"); 

because your .attr() will look for the name attribute of the first matching element (see the attr documentation)

+3
source share

Something like:

$ ("text field [name = 'this_name']") addClass ("MyClass") ;.

See: http://api.jquery.com/attribute-equals-selector/

+1
source share

All Articles