Here's the code that I want to modify:
a[href*="google"]
Now what I want to do is to add multiple keywords such as google, yahoo, etc. I tried doing like this and this worked fine:
a[href*="google"],[href*="yahoo"]
But now I'm trying to get data from array, e.g:
var array = ["google",yahoo","etc"]
What should I write now? Confused with the code. :(
These aren't working:
1. a[href*=array]
2. a[href*=[array]]
2 Answers 2
You need to create a jQuery selector like this:
a[href *= "<first term>"], a[href *= "<second term>"], a[href *= "..."]
You can use map and join to dynamically create this selector. Something like the following code should work:
var words = ["google", "yahoo", ...], terms, selector;
terms = $.map(words, function() {
return 'a[href *="' + this + '"]';
});
selector = terms.join(', ');
The map takes each element of the words array and creates each part of the selector (i.e. wrapping the word in the selector syntax) and then we join them together with a comma to create the jQuery selector.
Comments
You cannot use a shortcut for that. But you can build your selector dynamically:
var array = ['google', 'yahoo', 'etc'];
var selectorParts = [];
for(var i = 0; i < array.length; i++) {
selectorParts.push('a[href*=' + array[i] + ']');
}
var selector = selectorParts.join(',');
1 Comment
a[href*=ELEMENT]. Then it joins the array element using the separator ,