Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get particular instance of a class with a Div

How can I use jQuery to get a particular instance of a class(headerGrid) within a Div(products).

I need to be able to get an instance of the class 'headerGrid' classed span which says "Get this Text". The instance is represented as the value within swap2(). My code is as follows...

          <table id="products">
          ...
          <tr>
          <td>
          <a onclick="swap2(1);"><img src="images/products/thumbs/image.png"/></a>
          </td>
          <td valign="top" class="product-text">
          <span class="headerGrid">Get this Text</span><br /><br />
               text
          </td>
          </tr>
          ...
          </table>

E.g. if onclick="swap2(5);" then I need to get the 5th instance of '.headerGrid'

EDIT

Further more I need to select the text("Get this Text") rather then the object itself. Other wise it returns object [object Object].

I also tried selecting with .innerHTML which returns undefined.

like image 365
Philip Kirkbride Avatar asked Dec 22 '22 07:12

Philip Kirkbride


2 Answers

Use the eq() selector. Example:

$("#products span.headerGrid").eq(4) //Zero based index

With your function:

function swap2(n) {
    //Zero based index, subtract 1
    var theText = $("#products span.headerGrid").eq(n - 1).html();
    ...
}
like image 141
James Hill Avatar answered Dec 24 '22 00:12

James Hill


Using the :nth-child selector:

$('#products span.headerGrid:nth-child(5)')
like image 35
Clive Avatar answered Dec 24 '22 01:12

Clive