Reputation:
I need to compare my voice
attribute from array but unable to think how to do that I use forEach
, $.inArray
but didn't get any success.
What I need to do is that first I take the voice
attribute value and compare it with the items of array. Then, if the word matches with one item in the array, I change my CSS.
HTML:
<div voice="play">Play</div>
<div voice="test">Pause</div>
<div voice="stop">Stop</div>
JS:
var word = ['plays', 'play', 'clay', 'lay']
var command = $("[voice]").filter(function() {
return $(this).attr('voice') == word.forEach()
});
console.log(command);
var attr_array;
if (command.length) {
attr_array = command.attr('voice');
}
if (attr_array.length) {
command.css({
'color': 'red'
});
} else {
console.log("command did not match!");
}
Simply i want to know how to compare my array with the attribute's value.
Upvotes: 2
Views: 67
Reputation: 588
If you are using ES6 :
var word = ['plays', 'play', 'clay', 'lay']
var command = $("[voice]").filter(function() {
return word.includes($(this).attr('voice'));
});
console.log(command);
Or you could use Array.indexOf function :
var word = ['plays', 'play', 'clay', 'lay']
var command = $("[voice]").filter(function() {
return word.indexOf($(this).attr('voice'))>-1;
});
console.log(command);
Upvotes: 0
Reputation: 18381
You can use indexOf()
to check if your element's attribute is in word
or not.
var word = ['plays', 'play', 'test', 'lay']
$("[voice]").filter(function() {
return word.indexOf($(this).attr('voice')) > -1
}).css("color", "red");
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div voice="play">Play</div>
<div voice="test">Pause</div>
<div voice="stop">Stop</div>
However, if you want to do something else when the element's attribute is not in the array word
, each()
will be better than filter
. Filter returns only the elements whose attribute voice
is in the array word
whereas each
will loop over all the elements.
var word = ['plays', 'play', 'test', 'lay']
$("[voice]").each(function() {
if( word.indexOf($(this).attr('voice')) > -1){
$(this).css("color","red");
}
else{
//something else
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div voice="play">Play</div>
<div voice="test">Pause</div>
<div voice="stop">Stop</div>
Upvotes: 2