Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

cut a div and html inside it and paste it into a different div with jquery

Tags:

jquery

I have a 3rd party script in which i have no control over the html and can only modify basic css . I just wanted to know if its possible to cut a div and all the html inside it and paste it in a different div as soon as the page loads?

suppose we have

  <div id="example-one">
      <ul class="nav">
         <li class="nav-one"><a href="#featured" class="current">Billing Address</a></li>
      </ul>
      <div class="list-wrap">
          hello
      </div>
  </div>

and when the page loads jquery cuts the whole html specifying the div id "example-one" and paste it into a new div name it be "new-div". Is this possible ?

like image 659
user1001176 Avatar asked Jun 05 '13 22:06

user1001176


People also ask

How do you copy the content of a div into another div using jQuery?

First, select the div element which need to be copy into another div element. Select the target element where div element is copied. Use the appendTo() method to copy the element as its child.

How copy HTML using jQuery?

To clone an element using jQuery, use the jQuery. clone() method. The clone() method clones matched DOM Elements and select the clones. This is useful for moving copies of the elements to another location in the DOM.

Which jQuery function is used to change HTML of Div?

When . html() is used to set an element's content, any content that was in that element is completely replaced by the new content. Additionally, jQuery removes other constructs such as data and event handlers from child elements before replacing those elements with the new content.

What is jQuery detach?

jQuery detach() Method The detach() method removes the selected elements, including all text and child nodes. However, it keeps data and events. This method also keeps a copy of the removed elements, which allows them to be reinserted at a later time.


2 Answers

There is no cut & paste in DOM, you can append it(move it) to a different point in DOM:

$(document).ready(function() {
   $('#example-one').appendTo('#new-div');
});

In case that you want to create a div#new-div element and it doesn't exist:

$(document).ready(function() {
   $('<div/>', { id: 'new-div' }).appendTo('#somewhere').append($('#example-one'));
});
like image 180
undefined Avatar answered Sep 22 '22 19:09

undefined


I was able to find the answer to my question. I tried one jQuery function and it worked like a charm as I wanted. I am pasting the code so that it can be useful to anyone who has the exact problem as mine.

jQuery(document).ready(function() {
    $('#div1').insertAfter('.div2');
});

This will cut the div1 HTML and move it to div2.

like image 40
user1001176 Avatar answered Sep 24 '22 19:09

user1001176