views:

26

answers:

2

I want to "move" an id from one cell in a table to a relative cell in the table.

To simplify things, let's say I have this:

<tr><td></td><td id='a'></td><td></td><td></td><td></td></tr>

One of the cells has id='a' but I don't know which it will be. I simply want to make the one to the right of it have id='a'.

Getting the cell with id='a' and un-setting the id is simple enough:

var cell_a = $('#a');
cell_a.attr('id','');

However, I'm not sure how to get the cell to the right. I tried a few things with cell_a.parent().children() and cell_a.parent().find() but wasn't able to just pull out a list. Once I get the one to the right it will obviously be something like:

var new_cell_a = ?
new_cell_a.attr('id','a');
+3  A: 

Try cell_a.next()

like explained in this page: http://api.jquery.com/next/

endy_c
Okay, a related question; what if, instead of wanting to move right one cell, I want to move down one? I can get the proper row with `cell_a.parent().next()` but how do I get the cell?
kerkeslager
That would be `cell_a.parent().next().children()[0]`. You can find the complete list of traversal commands here: http://api.jquery.com/category/traversing/
endy_c
+2  A: 

You can use the next() method like this:

$("#a").removeAttr('id').end().next().attr('id', 'a');

The next() method is used there to find the element next to what is specified in previous selector $("#a") and then attr is used to change its id.

Sarfraz
`td[id='a']`? Why would you use such a complicated and slow selector as there is only one element with id `a`?
Harmen
@Harmen: Updated before seeing your comment :)
Sarfraz
If I set the id on the new element, will that unset it on the old one?
kerkeslager
@kerkeslager:No you will have to remove that explicitily, updated for that :)
Sarfraz