I have:
<a rel="9">Link 1</a>
<a rel="6">Link 2</a>
<a rel="3">Link 3</a>
<a rel="21">Link 4</a>
I want to trigger a click on the link with the highest 'rel' value. What is the most efficient way to write this?
I have:
<a rel="9">Link 1</a>
<a rel="6">Link 2</a>
<a rel="3">Link 3</a>
<a rel="21">Link 4</a>
I want to trigger a click on the link with the highest 'rel' value. What is the most efficient way to write this?
Try this.
var max = 0, index = 0;
$('a[rel]').each(function(i){
if(parseInt($(this).attr('rel'), 10) > max){
max = parseInt($(this).attr('rel'), 10);
index = i;
}
}).eq(index).trigger('click');
var maximum = null;
$('a[rel]').each(function() {
var value = parseInt($(this).attr('rel'));
maximum = (value > maximum) ? value : maximum;
});
$('a[rel="' + maximum + '"]').click();
Using the semi-famous map-array-apply trick:
modified HTML:
<a href="#" data-index="3">link 1</a>
<!-- et cetera -->
JS:
var tarr = $('a').map(function() {
return $(this).data('index');
}).toArray();
alert( Math.max.apply(Math,tarr) );
http://jsfiddle.net/mblase75/nsBYS/
By the way: triggering a click on an a hyperlink will trigger any JavaScript associated with the click event, but will not load the hyperlink. This is a security feature, and you have to circumvent it by extracting the href attribute. Not sure if this was your intention or not (since your sample code has no href attributes).