chris Frisina chris Frisina - 1 month ago 12
Javascript Question

Select sister elements of a table in jquery

I want to fill a td element by accessing other td s in the same row. How would I access them using jQuery?

In my situation, I have a table, and column 5 is populated by subtracting col 3 from col 4, and returning the result in col 5. I started to do it with a nested loop, but realized, that if I used the .each() on each col 5 td, it would be achievable if I could identify col 3 and 4 using jQuery.

Here is the fiddle.

The section to identify the elements is here:

$('section.techtable td:nth-child(5)').each(function() {
$(this).append(strinToMonthNumber($(START JQUERY),$(END JQUERY)));
})


I think that I would have to access the parent of $(this), and then the (3rd and 4th) child element?

I am also trying to avoid using span or class attributes on the TH or TD elements.

Answer

You can select one element (table cell in your case), and then use jQuery.prev() or jQuery.next() to select previous or next sibling element. In native DOM, you could use previousSibling/nextSibling (or previousElementSibling/nextElementSibling in modern browsers to skip non-element nodes) element properties for same purpose.

Based on your code example, something like this:

$('section.techtable td:nth-child(5)').each(function() {
    var cell5 = $(this),
        cell4 = cell5.prev(),
        cell3 = cell4.prev();

    cell5.append(strinToMonthNumber(cell3, cell4)));
})