Praveen M P
Praveen M P

Reputation: 11614

Get the data value of anchor tag using jquery

<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

Answers (5)

Heidar Ahmadi
Heidar Ahmadi

Reputation: 214

You can use:

$(this).attributes['data-index'].value;

Upvotes: 0

blackpanther
blackpanther

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

Sudharsan S
Sudharsan S

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); 
        });

Fiddle

Upvotes: 11

Milind Anantwar
Milind Anantwar

Reputation: 82241

use .data():

$(this).data('index')

Upvotes: 0

Felix
Felix

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); 
});

Fiddle Demo

Upvotes: 4

Related Questions