How is it possible to change positions?

1

How can I change positions? I've tried to store arrays and use array methods but it did not work.

<html>
<head>
<title>teste</title>
<script></script>
</head>
<body>

<ul class="lista">
     <!-- preciso que o tem 1 vire o item 7, e o 7 vire o  1  -->

     <li class="prim">Item 1</li>
     <li class="prim">Item 2</li>
     <li class="prim">Item 4</li>
     <li class="prim">Item 5</li>
     <li class="prim">Item 6</li>
     <li class="prim">Item 7</li>
</ul>

</body>

</html>
    
asked by anonymous 24.05.2015 / 16:54

1 answer

1

If you want to do it by dragging the user I suggest that you use a library like MooTools or jQuery.

If you just want to change positions you have 2 possibilities.

  • change the contents
  • change elements <li> keeping elements

# 1

Create a vriable that stores the contents of one of them and replaces the contents:

var lis = document.querySelectorAll('ul.lista li');
var temp = lis[0].innerHTML
lis[0].innerHTML = lis[5].innerHTML;
lis[5].innerHTML = temp;

jsFiddle: link

# 2

Using .insertBefore() you can put nr.7 before nr.2, and using .appendChild() it places at the end of the element indicated.

The syntax is:

  

elementPai insertBefore (newElement, elementReference);

That is:

var lis = document.querySelectorAll('ul.lista li');
lis[0].parentNode.insertBefore(lis[5], lis[1]); // para colocar o 7 no inicio 
lis[0].parentNode.appendChild(lis[0]);          // para colocar o 7 no inicio

jsFiddle: link

    
24.05.2015 / 17:58