Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

jquery
communitycreator

How to select an element by name with jQuery

abhilash

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 _name are selected using the [input$="_name"] selector expression. The elements with the student_first_name and student_last_name names are selected. Then, we change the background color of the elements to green.
  • Line 6: All the elements with named email are selected using the [input="_name"] selector expression. The element named email is selected. Then, we change the border color of the element to blue.
  • Line 8: All the elements with their name starting as zip are selected using the [input^="zip"] selector expression. The element named zip is selected. Then, we change the background color of the element to red.
  • Lines 10–11: The element is selected using the getElementsByName() method of the document object. 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.

RELATED TAGS

jquery
communitycreator
RELATED COURSES

View all Courses

Keep Exploring