Using jQuery, I am trying to get the data attribute of the following...
<a href="#" data-id="54" class="active">54</a>
var myid = jQuery("active").data("id");
Buit this is giving me an undefined error, where am I going wrong?
Missing "." before class selector. You need to do something like this to get the id attribute:
$(".active").attr("id");
Refer: https://api.jquery.com/attr/
You forgot to use class selector (.) .Moreover Class selector is not suited when you are looking to have multiple elements with same class (it will always return the first element).
var myid = jQuery(".active").data("id");
console.log(myid)
// if you have multiple elements with same class
jQuery(".active").each(function() {
let myid = $(this).data("id");
console.log(myid)
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.0/jquery.min.js"></script>
<a href="#" data-id="54" class="active">54</a>
<a href="#" data-id="55" class="active">55</a>
To find the attribute value of any tag you may use attr() method on the tag. Inside the attr() method you have to pass the custom data tag like data-{attribute-teag-name}
There are four different ways to get the result:
$(document).ready(function(){
var id = $("#custom").attr("data-customid");
console.log("attribute value with id -- ",id);
var id_1 = $(".active").attr("data-customid");
console.log("attribute value with class -- ",id_1);
var id_2 = $(".active").data("customid");
console.log("attribute value with class and data method -- ",id_2);
var id_3 = $("#custom").data("customid");
console.log("attribute value with id and data method -- ",id_3);
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<a href="#" data-customid="54" id="custom" class="active">54</a>
There is "." missing before class selector, You can get the data-id attribute value by:
$(".active").attr("data-id");
or
$(".active").data("id");
Getting data- attribute value by class so you have to use "." and by id "#" before the tag-name
Reference:
jQuery(".acitve")