How to select an element by name with jQuery
Attribute selectors
The CSS attribute selectors selects an element from the HTML using CSS properties.
An element can be selected using the name attribute with the following syntax:
[name[^$]="element_name"]
In the syntax above, ^ indicates ‘starts with’ and $ indicates ‘ends with.’
Example
Explanation
HTML:
The HTML consists of a form that contains four input elements. Every input element has a name associated with it. The dependency for jQuery is included in the HTML via the script tag in line 6.
JavaScript:
- Line 3: We define a function that triggers once the form button is clicked.
- Line 4: All the elements with their name ending as
_nameare selected using the[input$="_name"]selector expression. The elements with thestudent_first_nameandstudent_last_namenames are selected. Then, we change the background color of the elements to green. - Line 6: All the elements with named
emailare selected using the[input="_name"]selector expression. The element namedemailis selected. Then, we change the border color of the element to blue. - Line 8: All the elements with their name starting as
zipare selected using the[input^="zip"]selector expression. The element namedzipis selected. Then, we change the background color of the element to red. - Lines 10–11: The element is selected using the
getElementsByName()method of thedocumentobject. The selected element is passed to the$()selector function. This can be used as a jQuery object. The element’s background color is changed to yellow.