ppff
ppff

Reputation: 323

jQuery Selector to find content of td

My HTML structure looks something like below:

<div id="mainDiv">
<table></table>
<table></table>
<table>
<tr>
<td id="first">FirstCell</td><td id="second">SecondCell</td>
</tr>
<tr>
<td></td><td></td>
</tr>
</table>
</div>

Now I would like the find the content of second td based on the value of first td.

I have tried following but didn't seem to work.

$("#mainDiv tr td:contains('first')").each(function(){
                var secondCell = $(this).find('#second').value();
            });

Any help will be highly appreciated.

Upvotes: 4

Views: 18536

Answers (5)

chris Frisina
chris Frisina

Reputation: 19688

when you say find, do you mean using regex? or by relationship of/to the first.

If by relationship, then this will work

$("#mainDiv tr td:contains('first')").each(function(){
            var secondCell = $(this).next().html();
        });

.text() is sometimes better than .html() depending on what you are doing. See here for working example and more info.

If by Regex, you will have to provide what it is you are looking for in the first <td>.

Upvotes: 0

Ram
Ram

Reputation: 144659

as you are using each, instead of an id, class names should be used, try this:

$("#mainDiv tr td:contains('first')").each(function(){
    var secondCell = $(this).siblings('.second').text();
});

Upvotes: 0

Subir Kumar Sao
Subir Kumar Sao

Reputation: 8401

value is not a valid method.

You should use one of these as per requirement.

.html()  // for html content.
.text()  // for text content.
.val()   // for value attribute. Like value of input element.

Upvotes: 1

Prasenjit Kumar Nag
Prasenjit Kumar Nag

Reputation: 13461

Based on your html structure you can achieve what you want like this

$("#mainDiv tr td:contains('First')").each(function(){
                var secondCell = $(this).next().text();
                console.log(secondCell);
            });​

Working Fiddle

Like @Blender said .value() is not a function, use .text() instead.

Upvotes: 5

Blender
Blender

Reputation: 298076

.value() isn't a function. You're probably looking for .text().

Looking at your structure, I see that you are looking for #second relative to #first. Are there multiple elements that have id="second"? If so, you're going to run into a lot of trouble with jQuery, as the id attribute is meant to be unique to a single element. You should be using class instead of id if the property is used to identify more than one element.

Upvotes: 0

Related Questions