2

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?

phirschybar
  • 8,357
  • 12
  • 50
  • 66
  • 1
    Possible duplicate of this question? [jQuery: How to calculate the maximal attribute value of all matched elements?][1] [1]: http://stackoverflow.com/questions/7524583/jquery-how-to-calculate-the-maximal-attribute-value-of-all-matched-elements – d2burke Feb 01 '12 at 19:49
  • Be careful using the `rel` attribute, because it's supposed to be used for something completely different to what you're doing with it here – Gareth Feb 01 '12 at 20:08
  • @Gareth agreed -- using a data attribute like `data-index` would be a better choice here. As a fringe benefit, the `.data()` method will automatically parse the value as an integer. – Blazemonger Feb 01 '12 at 20:18
  • 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). – Blazemonger Feb 01 '12 at 20:24

3 Answers3

2

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');

Demo

ShankarSangoli
  • 69,612
  • 13
  • 93
  • 124
1
var maximum = null;

$('a[rel]').each(function() {
  var value = parseInt($(this).attr('rel'));
  maximum = (value > maximum) ? value : maximum;
});

$('a[rel="' + maximum + '"]').click();
Bassam Mehanni
  • 14,796
  • 2
  • 33
  • 41
1

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).

Community
  • 1
  • 1
Blazemonger
  • 90,923
  • 26
  • 142
  • 180