Roch
Roch

Reputation: 22041

JQuery select an element inside a td

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:

alt text

Upvotes: 12

Views: 98278

Answers (5)

Bjarki Hei&#240;ar
Bjarki Hei&#240;ar

Reputation: 3147

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.

Upvotes: 10

Josh Stodola
Josh Stodola

Reputation: 82483

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.

Upvotes: 0

cupakob
cupakob

Reputation: 8531

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

Upvotes: -2

Vincent Ramdhanie
Vincent Ramdhanie

Reputation: 103135

 $("table tr td .box")

Should do the trick.

Upvotes: 2

Sandman
Sandman

Reputation: 2379

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")

Upvotes: 19

Related Questions