Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery Selector

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.

like image 730
Lee McCroskey Avatar asked Apr 22 '26 20:04

Lee McCroskey


2 Answers

If your "main" table is not inside another table, you could do:

$('table a:not(table table a)')

or equivalently:

$('table a').not('table table a')

Update: Performance-wise, Patrick's answer is much better.

like image 173
Felix Kling Avatar answered Apr 28 '26 09:04

Felix Kling


I think I'd rather do this:

$('table').slice( 0, -1 ).find( 'a' );

Find all the tables, then reduce the set to all but the last, and finally do a .find() for the <a> elements.

The reason is that I'm heavily biased toward valid CSS selectors so that querySelectorAll can be successfully utilized by jQuery.

like image 32
user113716 Avatar answered Apr 28 '26 08:04

user113716



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!