Search code examples
javascriptjquerylocationhref

How to handle multiple instances of a single class in jQuery?


I'm not exactly sure how to handle multiple instances like this. I know in normal JS I can simply use [0] and such.

My code is this:

location.href = $('a.test').attr('href');

I need to handle both the first instance of test and the second. Is there a simple

location.href = $('a.test')[0].attr('href');

I'm missing or such?


Solution

  • $('a.test')[0] return a dom element reference which does not have the method attr(), so your script will fail

    use .eq(index)

    location.href = $('a.test').eq(0).attr('href');
    

    or

    location.href = $('a.test:eq(0)').attr('href');