Reputation: 181
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
Reputation: 85575
Try this:
$("td").each(function(){ if($(this).has("h1"){ $(this).next().append("click"); } });
Upvotes: 0
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
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