Home  >  Article  >  Web Front-end  >  How to Select Elements by Name Attribute in jQuery?

How to Select Elements by Name Attribute in jQuery?

DDD
DDDOriginal
2024-11-21 00:32:12654browse

How to Select Elements by Name Attribute in jQuery?

Selecting Elements by Name Attribute in jQuery

In jQuery, selecting elements by class name using $(".bold") is straightforward. However, difficulties arise when trying to select elements by name attribute, such as $("tcol1").

The Issue

Consider the following HTML:

<tr>
  <td>data1</td>
  <td name="tcol1" class="bold"> data2</td>
</tr>
<tr>
  <td>data1</td>
  <td name="tcol1" class="bold"> data2</td>
</tr>
<tr>
  <td>data1</td>
  <td name="tcol1" class="bold"> data2</td>
</tr>

While selecting by class ($(".bold")) works perfectly, selecting by name ($("tcol1")) seems futile. This is because jQuery requires more nuanced syntax to target elements by their name attribute.

Using jQuery Attribute Selector

To select elements by their name attribute, utilize the jQuery attribute selector. Here are a few common options:

  • Exact Match: $('td[name="tcol1"]')
  • Matching Prefix: $('td[name^="tcol"]')
  • Matching Suffix: $('td[name$="tcol"]')
  • Matching Substring: $('td[name*="tcol"]')

By employing these attribute selectors, you can easily target elements based on their name attributes.

The above is the detailed content of How to Select Elements by Name Attribute in jQuery?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn