Search code examples
javascriptjqueryhtmlfancybox

How to insert element into existing HTML by jQuery?


I have HTML code snippet:

<div class="main-photo" style="height: 304.875px;">
     <img class="big-thumb" src="blob:http://localhost:8080/cf4ffcff-7322-44dc-8c46-3c29ef165378" style="top: -27px;">
</div>

I need result when mouse hover :

<div class="main-photo" style="height: 304.875px;">
    <a class="fancybox fancybox.iframe" href="blob:http://localhost:8080/cf4ffcff-7322-44dc-8c46-3c29ef165378">
         <img class="big-thumb" src="blob:http://localhost:8080/cf4ffcff-7322-44dc-8c46-3c29ef165378" style="top: -27px;">
    </a>
</div>

I try something like this, use jQuery, when hover mouse over image (stub idea):

$('.main-photo').hover(function() {
    $('.main-photo ').append()..attr('class', 'fancybox fancybox.iframe');
});

but not work.


Solution

  • You will need to wrap/unwrap the anchor element, also it will be better to derive the source of the anchor dynamically from the image

    $('.main-photo').hover(function() {
      var $img = $(this).find('img'),
        $a = $('<a />', {
          'class': 'fancybox fancybox.iframe',
          href: $img.attr('src')
        });
      $img.wrap($a)
    }, function() {
      $(this).find('img').unwrap()
    });
    .main-photo {
      border: 1px solid grey;
    }
    .fancybox {
      border: 1px solid green;
      background-color: lightblue;
      display: inline-block;
      padding: 10px;
    }
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
    <div class="main-photo" style="height: 304.875px;">
      <img class="big-thumb" src="//placehold.it/64X64" style="top: -27px;">
    </div>