I'm trying to obtain this value for a javscript function
<a href="#" id="like" name="like" data-value="<?php echo $_GET['id'];?> " onclick="like(); return false;">
<img src="<?php echo $ROOT. "/assets/images/templates/like.png"?>" class="aligncenter" alt="" /></a>
I'd like to get the id which is the data-value.
I've tried using jquery selectors such as var id = $('a[data-value]').attr();
but obviously have it wrong.
Any help is appreciated.
I'm trying to obtain this value for a javscript function
<a href="#" id="like" name="like" data-value="<?php echo $_GET['id'];?> " onclick="like(); return false;">
<img src="<?php echo $ROOT. "/assets/images/templates/like.png"?>" class="aligncenter" alt="" /></a>
I'd like to get the id which is the data-value.
I've tried using jquery selectors such as var id = $('a[data-value]').attr();
but obviously have it wrong.
Any help is appreciated.
Share Improve this question asked Sep 23, 2013 at 13:53 nullnull 3,5177 gold badges48 silver badges93 bronze badges4 Answers
Reset to default 6Plain JavaScript has 2 Variants: getAttribute() and dataset:
var el = document.getElementById( 'like' );
el.getAttribute( 'data-value' );
el.dataset.value;
As you tagged this with jQuery as well, you could use data()
or attr()
:
$( '#like' ).data( 'value' );
$( '#like' ).attr( 'data-value' );
Using data()
you can only read the value, but not update it! data()
refers to a jQuery data object, which is just initialized with data-
fields of the HTML element, but does not update them!
jQuery's data()
will get the data attribute (but not set it) :
var id = $('#like').data('value');
or plain JS
var id = document.getElementById('like').getAttribute('data-value');
use .data()
var id= $('#like').data('value');
.data() Store arbitrary data associated with the matched elements
You need to use data
to retrieve a data attribute:
var id = $('a[data-value]').data('value');
Or, given that the a
element has an id
:
var id = $('#like').data('value');
You can use attr()
, but note this will only get data
attributes which are attached to the DOM element and as such is not considered good practice. Data attributes added using jQuery will only appear in the data cache and available through data()
so cannot be retrieved in this way:
var id = $('#like').attr('data-value');