How is it possible to change position li?

Asked

Viewed 657 times

1

How is it possible to change position li? I’ve tried to store in arrays and use methods for array but it didn’t 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>

1 answer

1

If you want to do it by user drag I suggest you use a library like Mootools or jQuery.

If you only want to change position you have 2 possibilities.

  • change the content
  • exchange the elements <li> retaining the elements

#1

Creates a safe to store 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: http://jsfiddle.net/s1w35ro2/1/

#2

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

the syntax is:

elementPai.insertBefore(newElement, elementReference);

That is to say:

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: http://jsfiddle.net/s1w35ro2/

Browser other questions tagged

You are not signed in. Login or sign up in order to post.