Reputation: 11614
<ul>
<li><a id="tab1" data-index="0" name="tab" href="#">abc</a></li>
<li><a id="tab2" data-index="1" name="tab" href="#">def</a></li>
<li><a id="tab3" data-index="2" name="tab" href="#">ijk</a></li>
</ul>
Here is my Question
If I click on any Anchor tag, I want to get the [data-index]
value of selected item.
and am not supposed to use Id Selector or Class selector
This is what I tried using jQuery but it's not working
$("a[name=tab]").on("click", function () {
var a = $(this).getAttribute("data-index");
alert(a);
});
Thank u
Upvotes: 3
Views: 33125
Reputation: 11486
You can use:
$("a[name=tabs]").on("click", function () {
var a = $(this).data('index');
alert(a);
});
I would definately have a look at this link because it shows the change in HTML 5 and how we can use jQuery to effectively get information from HTML 5 data attributes.
Upvotes: 1
Reputation: 15393
use .attr()
in jquery
$("a[name=tabs]").on("click", function () {
var a = $(this).attr("data-index");
alert(a);
});
or use .data()
in jquery
$("a[name=tabs]").on("click", function () {
var a = $(this).data("index");
alert(a);
});
Upvotes: 11
Reputation: 38102
You can use .data():
Return the value at the named data store for the first element in the jQuery collection, as set by data(name, value) or by an HTML5 data-* attribute.
var a = $(this).data("index");
Also note that the name
of your anchor is tab
not tabs
, so you need to use:
$("a[name=tab]").on("click", function () {
var a = $(this).data("index");
alert(a);
});
Upvotes: 4