Wednesday, February 29, 2012

jQuery: How to move an element

Sometimes we need to move an element in order to apply a quick-fix or something part of an effect that you want to achieve. Or maybe you are just playing around jQuery and you want to move or transfer an element into another element.

Moving an element using prependTo()

HTML:

<html>
<head>
  <title>Moving an Element using jQuery</title>
</head>
<div id="content">
  <h3>Title</h3>
  <p>Content 1</p>
  <p>Content 2</p>
</div>
<div id="footer">
  <p>Footer 1</p>
  <p>Footer 2</p>
</div>
</body>
</html>

jQuery: Select h3 and move inside the #footer as first element.
Note: Make sure to put this above the closing body tag </body>

<script type="text/javascript">
(function(){
  $('h3').prependTo('#footer');
})();
</script>

Result:

<html>
<head>
  <title>Moving an Element using jQuery</title>
</head>
<div id="content">
  <p>Content 1</p>
  <p>Content 2</p>
</div>
<div id="footer">
  <h3>Title</h3>
  <p>Footer 1</p>
  <p>Footer 2</p>
</div>
</body>
</html>

Moving an element using appendTo()

HTML:

<html>
<head>
  <title>Moving an Element using jQuery</title>
</head>
<div id="content">
  <h3>Title</h3>
  <p>Content 1</p>
  <p>Content 2</p>
</div>
<div id="footer">
  <p>Footer 1</p>
  <p>Footer 2</p>
</div>
</body>
</html>

jQuery: Select h3 and move inside the #footer as last element.
Note: Make sure to put this above the closing body tag </body>

<script type="text/javascript">
(function(){
  $('h3').appendTo('#footer');
})();
</script>

Result:

<html>
<head>
  <title>Moving an Element using jQuery</title>
</head>
<div id="content">
  <p>Content 1</p>
  <p>Content 2</p>
</div>
<div id="footer">
  <p>Footer 1</p>
  <p>Footer 2</p>
  <h3>Title</h3>
</div>
</body>
</html>

Note: insertBefore() works similar to prependTo() and insertAfter() works similar to appendTo().

No comments:

Post a Comment