Javascript DOM How to - Switch two elements with insertBefore








Question

We would like to know how to switch two elements with insertBefore.

Answer


<html>
  <head>
    <script type="text/javascript" src='http://code.jquery.com/jquery-1.5.2.js'></script>
    <script type="text/javascript">
        $(document).ready(function(){<!-- w  w w  .  j  a  v a  2 s  .co m-->
            $("p").insertBefore("#foo");

        });
    </script>
  </head>
  <body>
        1 <div id="foo">b</div><p>a</p>2
  </body>
</html>

The code above is rendered as follows: