简体   繁体   中英

Removing an image and adding it after div with jquery/javascript

Firsly here's the fiddle

I have an image with class "Full", and there is a div with class "group-of-buttons", I want to remove this img and add it after the div "group-of-buttons" with js, here's the HTML Code:

<img src="http://i.telegraph.co.uk/multimedia/archive/01622/nasa_1622185c.jpg" class="FULL"/>
<br><br>
<div class="group-of-buttons">
    <button class="one">One </button>
    <button class="two">Two </button>
</div>

Any help would be appreciated.

您可以使用insertAfter

$('.FULL').insertAfter('.group-of-buttons');

Should do what you want. It was just a matter of using the .insertAfter() jQuery method.

 $(document).ready(function() { var img = $('img.FULL'); img.insertAfter($('div.group-of-buttons')); }); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script> <img src="http://i.telegraph.co.uk/multimedia/archive/01622/nasa_1622185c.jpg" class="FULL" /> <br> <br> <div class="group-of-buttons"> <button class="one">One</button> <button class="two">Two</button> </div> 

$('.one').on('click', function() {
  var img = $('img.FULL');
  img.remove();
  img.insertBefore('.group-of-buttons');
});
$('.two').on('click', function() {
  var img = $('img.FULL');
  img.remove();
  img.insertAfter('.group-of-buttons');
});

I hope this was what you were looking to achieve example here: http://jsfiddle.net/atrifan/1ejmzkhp/

I added some extra id and div to your code. can you try this : buttons moves img from one div to another.

<script>
 function moveImage(movefrom,moveto,img_id) {
  imgtxt = document.getElementById(movefrom).innerHTML;
  imgobj = document.getElementById(img_id);
  document.getElementById(movefrom).removeChild(imgobj);
  document.getElementById(moveto).innerHTML = imgtxt;
 }
</script>
<div id="div1"><img src="http://i.telegraph.co.uk/multimedia/archive/01622/nasa_1622185c.jpg" class="FULL" id="img"/></div>
<br><br>
<div class="group-of-buttons">
<button class="one" onclick="moveImage('div2','div1','img');">One </button>
<button class="two" onclick="moveImage('div1','div2','img');">Two </button>
</div>
<br>
<div class="secondary-div" id="div2">
    Secondary Div
</div>

I hope it helps.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM