I have a fairly simple dynamic html structure of a table that contains links and the possibility that it will contain a second table with links. I would like the change the html attribute for the links in the main table but not in the second.
My structure:
<table>
<tr><td><a href="www.google.com">link</a></td></tr>
<tr><td><a href="www.google.com">link</a></td></tr>
<tr><td><a href="www.google.com">link</a></td></tr>
<tr><td><a href="www.google.com">link</a></td></tr>
<tr><td><a href="www.google.com">link</a></td></tr>
<tr>
<td>
<table>
<tr><td><a href="http://stackoverflow.com">link</a></td></tr>
<tr><td><a href="http://stackoverflow.com">link</a></td></tr>
<tr><td><a href="http://stackoverflow.com">link</a></td></tr>
</table>
</td>
</tr>
So for example, I would like to change all the hrefs of “www.google.com” to “www.foo.com”. I am able to change the href attribute, but I am having issues with my selector b/c there are times where the second table will not exist.
My current selector looks like: $('table a').filter(':not(table:last a)')
I’m sure it is not the most effecient way to do it, but it was working till the possibility of no second table came into play.
If your “main” table is not inside another table, you could do:
or equivalently:
Update: Performance-wise, Patrick’s answer is much better.