Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to access hyperlink attributes in jquery when clicking

I'm trying to customize a confirmation dialog with a custom message embedded in the hyperlink tag, something like this:

<a class="confirmation" href="whatever.html" data-message="Are you sure?">the text</a>

and the js:

$('.confirm-delete').click(function(){
    return confirm('the content of the data-message attribute');
});

So my question is how can I access the data-message attribute? Thanks!

like image 898
petekaner Avatar asked Nov 25 '25 08:11

petekaner


1 Answers

Well you are using jQuery, so use the .data() function to get data-* attributes.

Also using simple JS this.dataset.message will work on most of the new browsers, but going back to primitive browsers, use this.getAttribute('data-message'). But in the case which you are using jQuery, .data() is preferred.

$('.confirmation').click(function(){
  return confirm($(this).data('message'));
});

function message(element){
  return confirm(element.dataset.message);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<a class="confirmation" href="whatever.html" data-message="Are you sure?">Use jquery</a>
<br/>
<a href="whatever.html" onclick="return message(this);" data-message="Are you sure?">Use simple JS</a>
like image 101
rrk Avatar answered Nov 26 '25 21:11

rrk



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!