Multiple data-rel values

264 views Asked by At

I have multiple objects with data-rel values and for only some of them I would like to be able to, let's say, change to color of the content to red like so:

HTML

<p data-rel="1">1</p>
<p data-rel="2">2</p>
<p data-rel="3">3</p>
<p data-rel="4">4</p>

SCRIPT

 $("[data-rel='1'], [data-rel='3']").hover(function (){
        $( this ).css({
            'color': 'red'
        });
    });

This works but it can get pretty boring to write for each value [data-rel='3'] so I was wondering, is there a way to do this something like: [data-rel='1, 3'] instead of [data-rel='1'], [data-rel='3']?

2

There are 2 answers

4
Amit Joki On

Yes, you do have a cool way of doing it

var arr = [1, 3]; // add the numbers you want
$('[data-rel]').filter(function(x) {
    return arr.indexOf(+$(this).data("rel")) > -1; // check if it is present
}).hover(function() {
    $(this).css('color', 'red');
});
6
PeterKA On

If you're interested in the odd numbered ones only, you could do it as follows:

$('[data-rel]').filter(function(i,p) { 
    return +$(p).data('rel') % 2 === 1;
})
.hover(function() {
    $( this ).css({
        'color': 'red'
    });
});

$('[data-rel]').filter(function(i,p) { 
    return +$(p).data('rel') % 2 === 1;
})
.hover(function() {
    $( this ).css({
        'color': 'red'
    });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p data-rel="1">1</p>
<p data-rel="2">2</p>
<p data-rel="3">3</p>
<p data-rel="4">4</p>