Get a specific instance of a class with Div

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

I need to be able to get an instance of the classGrid class called "Get this text." An instance is represented as a value in 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> 

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

EDIT

Next, I need to select the text ("Get this text"), and not the object itself. Another wise returns an object [object Object].

I also tried selecting with .innerHTML, which returns undefined.

+4
source share
3 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(); ... } 
+4
source

Using : nth-child selector :

 $('#products span.headerGrid:nth-child(5)') 
+4
source

Use $("#products span.headerGrid:nth-child(5)") , which will return the 5th span with the headerGrid class to your element with the identifier products .

The swap function might look like this:

 function swap(n){ var element = $("#products span.headerGrid:nth-child(" + n + ")"); //Rest of code } 

A small notice: you mentioned DIV(products) in your question, but your code shows table .

+3
source

All Articles