12

I am very new to jQuery and JavaScript. I have a small question. Let's say i have a HTML table like the following

<Table id="mytable">
 <tr id="element">
  <td>value</td>
  <td>text</td>
</tr>
</Table>

In the above example i know the row id and i want to change the value of the second column of the row with that particular id.

I need a result something like the following:

 <Table id="mytable">
 <tr id="element">
  <td>value</td>
  <td>ChangedText</td>
</tr>
</Table>

So my question is: how can I select the 2nd column of the first row with a given id in order to change the value?

6
  • do you want to select ALL the second columns of every row, or only the second column of the first (on nth) row? Commented Sep 1, 2010 at 22:40
  • 1
    @Yanick - OP was pretty clear: "i know the row id and i want to change the value of the second column of the row with that particular id"
    – user113716
    Commented Sep 1, 2010 at 22:42
  • @patric dw, but an answer was suggesting a selector to find all the second TD of every row, so just wanted to make sure. As you can see, my answer presume what the OP is suggesting... Commented Sep 1, 2010 at 22:44
  • @Yanick - Which answer is that?
    – user113716
    Commented Sep 1, 2010 at 22:46
  • 1
    @Yanick - No, @Gert is using the #element ID selector that is specific to the row with that ID, so the other rows will not be affected. The td:nth-child(2) in the selector must be a descendant of #element.
    – user113716
    Commented Sep 1, 2010 at 22:54

3 Answers 3

24
$("#element td:nth-child(2)").text('ChangedText');

Here's an example.

0
17

something like

$('#mytable tr:eq(0) td:eq(1)').text('ChangedText');

will select the first row, second column (0 based) of the given element (TABLE). In your case, since you know the row id :

$('#mytable #element td:eq(1)').text('ChangedText');

or simply

$('#element td:eq(1)').text('ChangedText');
3
  • 1
    I like this one, because when I think of iterations I always see 0 based index. When 2 actually means the second item, I start looking over my shoulder thinking something bad is going to happen today.
    – eaglei22
    Commented Jan 18, 2017 at 15:37
  • This is why CSS is meant for designers (1, 2, 3, 4...) and JavaScript for programmers (0, 1, 2, 3...) :) Commented Jan 18, 2017 at 15:41
  • :) Yes, as a programmer primarily, I am extremely thankful for bootstrap!
    – eaglei22
    Commented Jan 18, 2017 at 15:45
2

Gert's code is how I would have implemented what you are asking so I won't repost it. However since you are new to jquery/javascript, you might like this tool I use to make sure my selectors are working http://www.woods.iki.fi/interactive-jquery-tester.html.

Cheers, Joe

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.