323

How to get an element with its name attribute with jQuery?

Is there anything (like # for id and . for class) for name in jQuery?

Madara's Ghost
  • 172,118
  • 50
  • 264
  • 308
MSajjadi
  • 3,809
  • 3
  • 23
  • 20

5 Answers5

605
$('[name="ElementNameHere"]').doStuff();

jQuery supports CSS3 style selectors, plus some more.

See more

Madara's Ghost
  • 172,118
  • 50
  • 264
  • 308
36

You can use:

jQuery('[name="' + nameAttributeValue + '"]');

this will be an inefficient way to select elements though, so it would be best to also use the tag name or restrict the search to a specific element:

jQuery('div[name="' + nameAttributeValue + '"]'); // with tag name
jQuery('div[name="' + nameAttributeValue + '"]',
     document.getElementById('searcharea'));      // with a search base
steveukx
  • 4,370
  • 19
  • 27
  • 2
    Selectors usually work from right to left, meaning regardless of elements, it would still search the name first, then the element. Hence your extended answer has little meat. But still, good answer :) – Madara's Ghost Mar 13 '12 at 07:45
  • Quite right - it's the inclusion of the context that is more important, browsers without querySelectorAll or getElementsByName (special case for using the name attribute) would use getElementsByTagname('*') in sizzle making it better to use jQuery('#container').find('[name=someName]') than just jQuery('[name=someName]') - it might not be that important given browser support for getElementsByName though – steveukx Mar 13 '12 at 09:03
  • How to get element by class? – aspiring May 28 '15 at 08:04
  • Use `.classname` - examples can be found in the [MDN Documentation](https://developer.mozilla.org/en-US/docs/Web/CSS/Class_selectors) – steveukx May 29 '15 at 12:07
29

it's very simple getting a name:

$('[name=elementname]');

Resource:

http://www.electrictoolbox.com/jquery-form-elements-by-name/ (google search: get element by name jQuery - first result)

Madara's Ghost
  • 172,118
  • 50
  • 264
  • 308
Joeri Minnekeer
  • 592
  • 5
  • 17
16
jQuery("[name='test']") 

Although you should avoid it and if possible select by ID (e.g. #myId) as this has better performance because it invokes the native getElementById.

SharpC
  • 6,974
  • 4
  • 45
  • 40
Simon Edström
  • 6,461
  • 7
  • 32
  • 52
10

You could always do $('input[name="somename"]')

Moo-Juice
  • 38,257
  • 10
  • 78
  • 128