Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
35
rated 0 times [  40] [ 5]  / answers: 1 / hits: 21087  / 10 Years ago, mon, september 15, 2014, 12:00:00

I have this html:



<table>
<tr>
<td>
Set right order
</td>
<td>
<span style = display: block;>asd | <a href = '#' onclick = moveChoiceTo(this, -1);>&uarr;</a><a href = '#' onclick = moveChoiceTo(this, 1);>&darr;</a></span>
<span style = display: block;>dsa | <a href = '#' onclick = moveChoiceTo(this, -1);>&uarr;</a><a href = '#' onclick = moveChoiceTo(this, 1);>&darr;</a></span>
<span style = display: block;>qwe | <a href = '#' onclick = moveChoiceTo(this, -1);>&uarr;</a><a href = '#' onclick = moveChoiceTo(this, 1);>&darr;</a></span>
<span style = display: block;>ewq | <a href = '#' onclick = moveChoiceTo(this, -1);>&uarr;</a><a href = '#' onclick = moveChoiceTo(this, 1);>&darr;</a></span>
</td>
</tr>
</table>


And this JS:



function moveChoiceTo(elem_choice, direction)
{
var curr_index = -1; //index of elem that we should move
var td = elem_choice.parentElement.parentElement; //link to TD

for (var i = 0; i < td.children.length; i++) //determine index of elem that called this function
if (td.children[i].children[0] == elem_choice)
{
curr_index = i;
break;
}

if (curr_index == -1)
return;

if (curr_index == 0 && direction < 0) //if nowhere to move
return;

if (curr_index == td.children.length - 1 && direction > 0) //if nowhere to move
return;

var curr_child = td.children[curr_index]; //save current elem into temp var
td.children.splice(curr_index, 1); //here I getting exception that splice isn't supported by object, but arent this is array?
td.children.splice(curr_index + direction, 0, curr_child); //attempt to insert it
}


I getting exception that splice isn't supported, but this supposed to be an array and support this method?
What other ways I have to change children order?


More From » html

 Answers
28

I will add the answer with simpler (and better) approach:



function moveChoiceTo(elem_choice, direction) {

var span = elem_choice.parentNode,
td = span.parentNode;

if (direction === -1 && span.previousElementSibling) {
td.insertBefore(span, span.previousElementSibling);
} else if (direction === 1 && span.nextElementSibling) {
td.insertBefore(span, span.nextElementSibling.nextElementSibling)
}
}


The key idea is using insertBefore method properly. You also don't need to remove anything from DOM.



Demo: http://jsfiddle.net/dq8a0ttt/


[#69450] Friday, September 12, 2014, 10 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
stacie

Total Points: 476
Total Questions: 92
Total Answers: 102

Location: Bosnia and Herzegovina
Member since Tue, Mar 29, 2022
2 Years ago
stacie questions
Fri, Jun 26, 20, 00:00, 4 Years ago
Thu, Jan 23, 20, 00:00, 4 Years ago
Fri, Aug 30, 19, 00:00, 5 Years ago
Fri, Aug 2, 19, 00:00, 5 Years ago
;