Danny Cooper
Danny Cooper

Reputation: 355

jQuery OR operator?

I want to check if an element has a data attribute of either data-youtube-id or data-youtube-id and run something based on that (basically prevent a link from following through).

How can I check for both attributes at once?

This is what I'm using and it's not working correctly:

HTML

<a href="#" data-youtube-id="xxxxxx">link title 1</a>
<a href="#" data-vimeo-id="xxxxxx">link title 2</a>

jQuery

$('a').click(function(e) {
    if ($(this).data('youtube-id, vimeo-id')) {
        e.preventDefault();
    }
});

I also tried similar jQuery using attr(); instead of data(); (also didn't work):

$('a').click(function(e) {
    if ($(this).attr('data-youtube-id, data-vimeo-id')) {
        e.preventDefault();
    }
});

Upvotes: 0

Views: 286

Answers (1)

Arun P Johny
Arun P Johny

Reputation: 388316

use has attribute selector along with is()

if ($(this).is('[data-youtube-id], [data-vimeo-id]')){
}

Both data(string) & attr(string) are getter methods which gets the value of said data/attribute value


As @Brilliand said you can filter out the elements before you register the click handler.. if this was your complete click handler code

$('a').filter('[data-youtube-id], [data-vimeo-id]').click(function (e) {
    e.preventDefault();
});

Upvotes: 4

Related Questions