I'm with a little problem. I've got a few buttons, each with a different data-function=""
attribute. I want to execute a little script to check which of the buttons has been clicked.
<a href="#" class="functionButton" data-function="blogFunctionaliteit">Blog</a>
<a href="#" class="functionButton" data-function="offerteFunctionaliteit">Offerte</a>
<a href="#" class="functionButton" data-function="overzichtFunctionaliteit">Offerte</a>
I simply want a script that says
if $(this) has <data-function="blogFunctionaliteit"> { }
if $(this) has <data-function="offerteFunctionaliteit"> { }
if $(this) has <data-function="overzichtFunctionaliteit"> { }
else { // do nothing }
I've tried lots of thing, but everything doesn't seem to be working, including
if ($(this).attr('data-function', 'blogFunctionaliteit') { }
- Which results in a yes, always, as it only checks if the object has the first parameter, instead of checking them both.
Thanks in advance for writing the correct jQuery code or could advice me to use something else.
Use the hasAttribute() method to check if a data attribute exists, e.g. if (el. hasAttribute('data-example')) {} . The hasAttribute method returns true if the provided attribute exists, otherwise false is returned.
Use the querySelector method to get an element by data attribute, e.g. document. querySelector('[data-id="box1"]') . The querySelector method returns the first element that matches the provided selector or null if no element matches the selector in the document.
The jQuery. hasData() method provides a way to determine if an element currently has any values that were set using jQuery. data() . If there is no data object associated with an element, the method returns false ; otherwise it returns true .
To retrieve a data-* attribute value as an unconverted string, use the attr() method. Since jQuery 1.6, dashes in data-* attribute names have been processed in alignment with the HTML dataset API. $( "div" ).
You can do:
if ($(this).attr('data-function') == 'blogFunctionaliteit') { }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With