3

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.

premsh
  • 213
  • 3
  • 6
  • 16

5 Answers5

4

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.

Prasenjit Kumar Nag
  • 13,391
  • 3
  • 45
  • 57
1

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.
Subir Kumar Sao
  • 8,171
  • 3
  • 26
  • 47
0

.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.

Blender
  • 289,723
  • 53
  • 439
  • 496
0

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();
});
Ram
  • 143,282
  • 16
  • 168
  • 197
0

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>.

Community
  • 1
  • 1
chris Frisina
  • 19,086
  • 22
  • 87
  • 167