JQuery selector

I have a pretty simple dynamic html table structure containing links and the possibility that it will contain a second table with links. I would like to 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 hrefs from "www.google.com" to "www.foo.com". I can change the href attribute, but I am having problems with my b / c selector when there is a time when the second table will not exist.

My current selector is as follows: $('table a').filter(':not(table:last a)')

I'm sure this is not the most efficient way to do this, but it worked until the second table entered the game.

+3
source share
5 answers

"" , :

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

:

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

: , .

+5

, :

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

, , , , , .find() <a> .

, CSS, querySelectorAll jQuery.

+1

.
:

$( "body > table > tr > td > a" )

0

ID ( ):

$('#maintable > tbody > tr > td > a')

#maintable - .

Edit: You will also want to add the tag <tbody>to the table (for the reasons indicated in the comments).

This uses the basic CSS selector in new browsers and does not require any jQuery magic unless you are using an older browser.

0
source

If you can change dynamically generated HTML, you should really provide each table with an ID property:

<table id="table1"> ...
    <table id="table2"> ...
    </table>
</table>

Then your selectors may just be

$('#table1').find('a')

This does not really answer your question, but this design is much more convenient and easier to change.

0
source

Source: https://habr.com/ru/post/1783301/


All Articles