Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to swap HTML elements in javascript?

Tags:

javascript

dom

I am using classic Javascript for DOM scripting, i have a set of DIV's in a container DIV. On click event of child DIV's, i want that the child DIV which has caused event to be swaped with the DIV above it.. my code goes here..

 <div id="container">
        <div onclick="swapDiv(event);">1</div>
        <div onclick="swapDiv(event);">2</div>
        <div onclick="swapDiv(event);">3</div>
 </div>

if DIV 2 has been clicked it should be swap with DIV 1

like image 610
Harish Kurup Avatar asked May 31 '10 11:05

Harish Kurup


People also ask

How can I change an element's class with JavaScript?

To change all classes for an element:document. getElementById("MyElement"). className = "MyClass"; (You can use a space-delimited list to apply multiple classes.)


1 Answers

This code will do what you want (if you want to swap the selected with the first child element). In case you want something else you need to be more precise.

<script type="text/javascript">
  function swapDiv(event, elem) {
    elem.parentNode.insertBefore(elem, elem.parentNode.firstChild);
  }
</script>


<div id="container">
  <div onclick="swapDiv(event,this);">1</div>
  <div onclick="swapDiv(event,this);">2</div>
  <div onclick="swapDiv(event,this);">3</div>
</div>
like image 189
Thariama Avatar answered Sep 16 '22 17:09

Thariama