jQuery Method How to - Get data attribute with data() method








Question

We would like to know how to get data attribute with data() method.

Answer


<!DOCTYPE html>
<html>
<head>
<script type='text/javascript'
  src='http://code.jquery.com/jquery-1.7.js'></script>
<script type='text/javascript'>
$(function(){<!--   w  w w .j av  a  2  s.c  o m-->
    function alertIt(id, descr) {
        console.log(id + ' ' + descr);
    }
    $('button').click(function() {
        var $this = $(this),
            id = $this.data('myid'),
            descr = $this.data('mydescr');
        alertIt(id , descr );
    });
});
</script>
</head>
<body>
  <button data-myId="1001" data-myDescr="The thing we delete">Click me!</button>
</body>
</html>

The code above is rendered as follows: