I'm using the jQuery quicksand plugin. I need to get the data-id of the clicked item and pass it to a webservice.
How do I get the data-id attribute? I'm using the .on()
method to re-bind the click event for sorted items.
$("#list li").on('click', function() {
// ret = DetailsView.GetProject($(this).attr("#data-id"), OnComplete, OnTimeOut, OnError);
alert($(this).attr("#data-id"));
});
<script src="https://code.jquery.com/jquery-3.3.1.slim.min.js"></script>
<ul id="list" class="grid">
<li data-id="id-40" class="win">
<a id="ctl00_cphBody_ListView1_ctrl0_SelectButton" class="project" href="#">
<img src="themes/clean/images/win.jpg" class="project-image" alt="get data-id" />
</a>
</li>
</ul>
Accessing data attribute with its own
id
is bit easy for me.$("#Id").data("attribute");
Surprised no one mentioned:
Here is the working example: https://jsfiddle.net/ed5axgvk/1/
If we want to retrieve or update these attributes using existing, native JavaScript, then we can do so using the getAttribute and setAttribute methods as shown below:
Through JavaScript
Through jQuery
Read this documentation
I use $.data - http://api.jquery.com/jquery.data/
To get the contents of the attribute
data-id
(like in<a data-id="123">link</a>
) you have to useor
.data()
(if you use newer jQuery >= 1.4.3)and the part after
data-
must be lowercase, e.g.data-idNum
will not work, butdata-idnum
will.If you are not concerned about old IE browsers, you can also use HTML5 dataset API
HTML
JS
Demo: http://html5demos.com/dataset
Full browser support list: http://caniuse.com/#feat=dataset