w3resource

jQuery: Move one DIV element inside another

jQuery Practical exercise Part - I : Exercise-12

Move one DIV element inside another using jQuery.

Move the following 
<div id="source">
...
</div>
To 
<div id="destination">
...
</div>

Sample solution :

HTML Code :


<!DOCTYPE html>
<html>
<head>
<script src="https://code.jquery.com/jquery-git.js"></script>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>Move one DIV element inside another.</title>
</head>
<body>
<div id="nonSelected">
<!--Declaring BUTTON TAGS -->
<button id="btnDefault" onclick="moveButton(this)" type="button">Button1</button>
    <button id="btnPrimary" onclick="moveButton(this)" type="button" >Button2</button>
	
	  <button id="btnDanger" onclick="moveButton(this)" type="button">Button3</button>
	  
	  </div>
	  <div id="selected">
	  </div>
	  </body>
	  </html>

CSS Code :


#nonSelected{
    position: absolute;
    top: 10px;
    left: 10px;
    width: 180px;
    height: 180px;
    background-color: #884333;
    border-width: 1px;
    border-style: dotted;
    border-color: black;
    padding: 10px;
}

#selected{
    position: absolute;
    top: 10px;
    left: 200px;
    width: 180px;
    height: 180px;
    background-color: #498933;
    border-width: 1px;
    border-style: dotted;
    border-color: black;
    padding: 10px;
}

JavaScript Code :


function moveButton(elem){
    if( $(elem).parent().attr("id") == "nonSelected" ){
        $(elem).detach().appendTo('#selected');
    }
    else{
        $(elem).detach().appendTo('#nonSelected'); 
    }
}

See the Pen jquery-practical-exercise-12 by w3resource (@w3resource) on CodePen.


Contribute your code and comments through Disqus.

Previous: Create a division using jQuery with style tag.
Next: Select values from a JSON object using jQuery.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Become a Patron!

Follow us on Facebook and Twitter for latest update.

It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.

https://w3resource.com/jquery-exercises/part1/jquery-practical-exercise-12.php