Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use 'If $(this) has data-attribute'

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.

like image 422
Sander Schaeffer Avatar asked Mar 17 '14 13:03

Sander Schaeffer


People also ask

How do you check if an element has a data attribute?

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.

How do I select an element by a data attribute?

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.

How do you check data is exist or not in jQuery?

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 .

How get data attribute in jQuery?

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" ).


1 Answers

You can do:

if ($(this).attr('data-function') == 'blogFunctionaliteit') { }
like image 87
Felix Avatar answered Nov 26 '22 20:11

Felix