0

How can extract in Jquery "data" value from this:

<a href="#" data="12" class="virus">12</a>
<a href="#" data="123" class="virus">another but no 123</a>
<a href="#" data="124" class="virus">need number from data=""</a>

to onClick event from each of these anchor with same classes? Thank you:).

2 Answers 2

4

$('.virus').click(function() {


  alert($(this).attr('data'))
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<a href="#" data="12" class="virus">12</a>
<a href="#" data="123" class="virus">another but no 123</a>
<a href="#" data="124" class="virus">need number from data=""</a>

use : .attr()

Description: Get the value of an attribute for the first element in the set of matched elements.

I suggest you make the data="12" into something like data-data="12" since data is not a valid attr.

Using .data()

Description: Store arbitrary data associated with the matched elements.

Then you can get it like

$(this).data('data')
Sign up to request clarification or add additional context in comments.

Comments

2

Using attr you can data data value. Try this:

$(".virus").click(function() {
    var data = $(this).attr("data"); // this will return data value of clicked link
    console.log(data)
});

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.