$("a[rel=example_1],a[rel=example_2],a[rel=example_3],a[rel=example_4],a[rel=example_5],a[rel=example_6],a[rel=example_7],a[rel=example_8],a[rel=example_9],a[rel=example_10]").fancybox({............
Hello, right now I have to manually enter those codes.
Is there an easy way to increment the numbers?
I know I can use something similar to a[rel=example_[1-10]]
. What is the correct syntax?
many thanks
$("a[rel=example_1],a[rel=example_2],a[rel=example_3],a[rel=example_4],a[rel=example_5],a[rel=example_6],a[rel=example_7],a[rel=example_8],a[rel=example_9],a[rel=example_10]").fancybox({............
Hello, right now I have to manually enter those codes.
Is there an easy way to increment the numbers?
I know I can use something similar to a[rel=example_[1-10]]
. What is the correct syntax?
many thanks
Share Improve this question edited Jul 25, 2012 at 4:33 Andrew M 4,28811 gold badges44 silver badges68 bronze badges asked Jul 25, 2012 at 4:05 oloolo 5,27115 gold badges60 silver badges96 bronze badges6 Answers
Reset to default 8You can use attribute starts with selector
a[rel^="example_"]
This will select all a
elements that have a rel
attribute that begins with "example_". I'd remend this over loops if you want to select all the elements that match that pattern.
If it's ok for you - you could go with
$('a[rel^="example_"]').
and it will match all a
that have rel
started with example_
Otherwise - use fine-filtering for it:
$('a[rel^="example_"]').filter(function() {
var match = $(this).prop('rel').match(/^example_(\d+)$/);
return match.length == 2 && parseInt(match[1]) <= 10;
})
The callback for the .filter()
explicitly checks if there is a number 1..10
after underscore
One potential solution would be to use a loop.
var element = 'a[rel=example_';
var elements = [];
for(var i = 1; i <= 10; i++){
elements.push(element + i.toString() + ']');
}
elements = elements.join(', ');
$(elements).fancybox()
Alternatively, if you wanted to match all elements with a rel
containing "example_", you can use an attribute selector like this:
$('a[rel*="example_"]').fancybox()
Finally, you could simply use a class to link all of the elements and select them by referencing the mon class.
use a for or while loop. Each time it iterates add one to a counter variable or if you use a for loop it will do that by itself.
heres some pseudocode:
var output
for count 1 to 10:
output .= $("a[rel='example'" + count];
next for
You could select all the element that start with "example_" using this selector:
$('a[rel^=example_])
You can generate a string to be used as a query:
var query = [];
for(var i=1;i<=10;i++)
query.push('a[rel=example_' + i + ']');
$(query.join(',')).fancybox({});