Home >Web Front-end >JS Tutorial >How to Retrieve a `data-id` Attribute Value Using jQuery?

How to Retrieve a `data-id` Attribute Value Using jQuery?

Susan Sarandon
Susan SarandonOriginal
2024-12-10 13:44:141057browse

How to Retrieve a `data-id` Attribute Value Using jQuery?

Accessing the data-id Attribute with jQuery

When working with the jQuery Quicksand plugin, it's often necessary to retrieve the 'data-id' attribute of clicked elements to pass information to various web services. Here's how to effectively obtain this attribute value:

The 'data-id' attribute can be accessed using the .attr() method in jQuery. The syntax is as follows:

$(this).attr("data-id")

This expression returns the value of the 'data-id' attribute as a string.

For example, if the clicked element has the following HTML:

<li data-id="id-40">...</li>

The following jQuery code will retrieve the 'data-id' attribute:

$("#list li").on('click', function() {
  // Get the data-id value
  var dataId = $(this).attr("data-id");
  // Use the dataId value as needed
});

Alternatively, you can use the .data() method for jQuery versions 1.4.3 and above. The .data() method returns the 'data-id' value as a native JavaScript type (e.g., number, boolean) rather than a string.

$(this).data("id")

Remember, when using the .data() method, the part after 'data-' must be lowercase. For instance, 'data-idNum' will fail, while 'data-idnum' will succeed.

The above is the detailed content of How to Retrieve a `data-id` Attribute Value Using 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