views:

37

answers:

4

I have a DYNAMICALLY generated Navigation div

<div id="WebPartWPQ9" >
 <table class="xm-ptabarea">
  <tbody>
   <tr>
    <td nowrap="" class="tab"><a href="/somelink.aspx">Overview</a></td>
    <td nowrap="" class="tab"><a href="/anothersomelink.aspx">Financials</a></td>
    <td nowrap="" class="tab"><a href="/somemorelink.aspx">Newsfeed</a></td>
   </tr>
  </tbody>
 </table>
</div>

Since there are no unique IDs, using jquery, i want to be able to attach an event to the "financial" tab link (using regular expressions selectors maybe?)

The value of the link will always be "Financials"

+2  A: 

It's super easy to select that <a> element using the :contains selector:

var $financialsLink = $('#WebPartWPQ9').find('td.tab > a:contains(Financials)');
Matt Ball
so many correct answers but you answered first
siimi
@siimi: thanks, much appreciated :)
Matt Ball
+2  A: 
$('#WebPartWPQ9 a:contains(Financials)')
Darin Dimitrov
You are missing the `live` part.
Sarfraz
@Sarfraz, what live part? The OP said that he wants to attach a click handler to a dynamically generated elements and that he needs to find the corresponding element. He doesn't mention anything about regenerating those elements dynamically once the click handler is attached, that's why I didn't talk about any `live` part. It would be unnecessary but of course it will depend on the exact scenario.
Darin Dimitrov
for my scenario, LIVE wouldn't be necessary as no regeneration is happening after the page has been loaded. Nice to learn about 'live' though as i didn't know about it before.
siimi
+2  A: 

Because it is dynamically generated, you can use .live() to handle events on elements created after the DOM loads.

$('#WebPartWPQ9 td.tab a:contains(Financials)').live('click', function() {
    // run code
});

Or if the #WebPartWPQ9 is present when the page loads, I'd probably use .delegate() instead.

$('#WebPartWPQ9').delegate('td.tab a:contains(Financials)', 'click', function() {
    // run code
});

Both of these use the :contains selector to target the one with "Financials".

patrick dw
You missed a comma!
Matt Ball
@Bears - I certainly did. Thanks. :o)
patrick dw
+1  A: 

You can use the :contains filter selector and live method like this:

$('.tab a:contains("Financials")').live('click', function(){
  // your code...
});
Sarfraz
i don't think quotes around Financials are necessary
Jason
@Jason: Yes it would work but it is good practice because you need to specify this for spaced strings. Also jquery docs use quotes.
Sarfraz
@sarfraz good point.
Jason