user3120015
user3120015

Reputation: 181

How to find a td element that contains a h1 and then add an onclick event to the td

I need to add an onclick event in Jquery. This is the criteria- if a td contains an h1 element, it needs to be added to the next td after the h1 element. For example I have the below html:

<table cellpadding="0" cellspacing="0" width="100%">
    <tr>
        <td colspan="2"><h1>Activity Packs</h1></td>
    </tr>
    <tr>
        <td colspan="2"><P>Test test Test test Test testTest test  Test test Test test Test test Test test Test test Test test Test test Test test Test test Test test Test test. Link: <a href="/products">I am a link</a></p></td>
    </tr>

The onclick event needs to be added to any "a" links instead the td after the h1 heading (the td with all the text text)

I don't have any control of the html so I can't add any id's or anything.

Upvotes: 3

Views: 269

Answers (3)

Bhojendra Rauniyar
Bhojendra Rauniyar

Reputation: 85575

Try this:

$("td").each(function(){ if($(this).has("h1"){ $(this).next().append("click"); } });

Upvotes: 0

dfsq
dfsq

Reputation: 193291

Try something like this:

$('table h1').closest('tr').next().find('a').on('click', function(e) {
    e.preventDefault();
    alert($(this).text());
});

Demo: http://jsfiddle.net/2yd3g/1/

Or more effective:

$('table h1').closest('tr').next().on('click', 'a', function(e) {
    ...
});

Upvotes: 2

uma
uma

Reputation: 2952

please try this

$('table tr td').each(function(){
   if($(this).find('h1')[0] != undefined){
     $($(this).find('h1')[0]).after('<a href="#">abc</a>');
   }
})

Upvotes: 1

Related Questions