Charles Okwuagwu Charles Okwuagwu - 5 months ago 12
jQuery Question

Accessing data-xxx attribute values with jquery

In Chrome console I can access(select) a required element and see the content as bellow:

> x = $(".sidebar-message a[data-id ='" + 2885 + "']")[0]

<a href=​"#" data-id=​"2885" data-uid=​"197025959" data-mobile=​"08021111134" data-lastname=​"Aliu" data-firstname=​"Isa" data-verified=​"true" data-assigned=​"false">​…​</a>​


Please how do i access the data-mobile , data-lastname etc using jQuery?

I tried
x.data-mobile
and
x[data-mobile]
, both are
undefined

Answer

I done this by following code :

<a href="#" data-id="2885" data-uid="197025959" data-mobile="08021111134" data-lastname="Aliu" data-firstname="Isa" data-verified="true" data-assigned="false">Check Attribute Value</a>
<span id="MobileValue"></span>

<script>
$("a").click(function(){
var mobileValue=$(this).attr("data-mobile");
$("#MobileValue").html(mobileValue);

});
</script>

Click Here for demo

Hope it helps you.

Comments