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
Release: 2024-12-10 13:44:14
Original
1005 people have browsed it

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")
Copy after login

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>
Copy after login

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
});
Copy after login

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")
Copy after login

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!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template