Chauhan
Chauhan

Reputation: 2591

How to replace inner html of one <div> to another </div> through jquery

I have two div tags: one contain an img tag inside and the other contain something else.

My first <div> contains an image. When I click on that image, or on some <div> having id insideFrameimg, it should show the second <div id="insideFrameobj" style="display:none;"> in place of <div id="insideFrameimg">.

<div id="insideFrameimg"><!-- first div-->
  <img src="my-image.png"/>
<div>

<div id="insideFrameobj"> <!--second div -->
  hello this is my description
</div>

I want to show the complete inner html of <div id="insideFrameobj"> in place of the first <div> when I click on <img> found inside the <div id="insideFrameimg"> using jQuery.

Upvotes: 1

Views: 4691

Answers (3)

Alnitak
Alnitak

Reputation: 339985

Just replace the contents of the div when the img is clicked:

$('#insideFrameimg img').click(function() {
    var contents = $('#insideFrameobj').html();
    $('#insideFrameimg').html(contents);
});

Upvotes: 0

Pavel Morshenyuk
Pavel Morshenyuk

Reputation: 11471

<div id="insideFrameimg"><!-- first div-->
  <img id="imgClick" src=""/>
  <div>

  <div id="insideFrameobj"> <!--second div -->
       hello this is my description>
   </div>

Something like this should help. It will replace first div content with second div content.

$('#imgClick').click(function () {
 $('#insideFrameimg').html($('#insideFrameobj').html());

});

Upvotes: 3

T.J. Crowder
T.J. Crowder

Reputation: 1075497

You can use the children function to get all children of insideFrameobj and use the append function to move them to insideFrameimg. That would typically be better than using innerHTML (or its jQuery wrapper html) because you're not tearing down the elements and recreating them (which would lose their event handlers). It's also more efficient.

That would look something like this:

$("#insideFrameimg").click(function() {
    $(this).append($("#insideFrameobj").children());
});

Naturally this leaves insideFrameobj empty, which seems to be what you want. If you don't, you might clone the children and append the clones:

$("#insideFrameimg").click(function() {
    $(this).append($("#insideFrameobj").children().clone());
//                           difference is here ---^
});

But if any of the children have id values, cloning them and adding the clones will result in an invalid document, since ids must be unique. (This is not just a theoretical issue; it will cause trouble for your page, if you ever use those IDs.)

Upvotes: 2

Related Questions