JQuery select an element inside a td

2019-04-20 09:52发布

问题:

I would like to select an element inside the td of one of my tables but I don't really understand the syntax. This is what I tried:

$("table > td:#box")

This is a sample of my table structure:

<div id="main">
<div id="today">
    <table id="list" width="100%" cellpadding="4" cellspacing="0" border="0" style="font-size: 10px; border-collapse:collapse;">
    <tr id="109008">
    <td class="tdstd">
    <a class="box" href="link"></a>
    </td>

Or With Chrome's DOM inspector:

回答1:

Well, "#box" means a DOM object with the id "box", as in it being a unique ID. You can select that one directly. But your code suggest that you have several elements with the id "box" which you have to change. You should assign a class to your element inside the TD, or if it's unique by being the only DIV or SPAN in the box, you can access it like this:

$("table td .box")

Note that the ">" selector means that TD has to be a direct child of TABLE, and I'm assuming you have at least a TR level in between, so that won't work either. My example above matches every element with the class "box" inside any TD that is a child to any TABLE.

Obviously I would set a class on the table as well, and use something like this:

$("table.boxes td .box")

Just so you don't accidentally selects things outside the scope you want to work in.


You have now added HTML so I'm editing my answer:

$("table#list a.box")


回答2:

The most efficient selector would be:

$('#list').find('a.box');

or:

$('a.box', $('#list')[0]);

By selecting the table id first you have set your scope to just the table and then you can search for the element that you need with in that table.

The second selector is just the same, you are selecting something and you are giving the scope as a second parameter.

It's just easier to read the first one.



回答3:

 $("table tr td .box")

Should do the trick.



回答4:

This selector...

table td a.box

tells jQuery to find the a tag with a class attribute that contains "box". And this a tag must be inside a td that is inside a table.



回答5:

I'm not sure, but i think, you need $("td#box")...