Reputation: 3163
I am trying to make image clickable and for this I want to wrap image within anchor tag, following is the code I tried but its generating anchor tag after image tag
This is the HTML code
jQuery(document).ready(function($){
jQuery('.fancybox-inner').append('<a href="#" class="new-img-holder"></a>');
jQuery('.fancybox-image').appendTo('new-img-holder');
});
<div class="fancybox-outer">
<div class="fancybox-inner" style="overflow: visible; width: 640px; height: 463px;">
<img class="fancybox-image" src="cine-sudarshan.jpg" alt="">
</div>
</div>
Upvotes: 1
Views: 2252
Reputation: 828
Try below code. It's easy if you use jquery wrap function.
jQuery(document).ready(function ($) {
$(".fancybox-image").wrap('<a href="javascript:void(0)" onclick="alert(\'clicked anchor tag\')" class="new-img-holder"></a>');
//jQuery('.fancybox-inner').wrap('<a href="#" class="new-img-holder"></a>');
//jQuery('.fancybox-image').wrap('new-img-holder');
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="fancybox-outer">
<div class="fancybox-inner" style="overflow: visible; width: 640px; height: 463px;">
<img class="fancybox-image" src="http://imgsv.imaging.nikon.com/lineup/lens/zoom/normalzoom/af-s_dx_18-140mmf_35-56g_ed_vr/img/sample/sample1_l.jpg" alt="">
</div>
</div>
Upvotes: 0
Reputation: 535
$(".fancybox-image").wrap('<a href="#" class="new-img-holder"></a>');
Upvotes: 0
Reputation: 3242
Just use wrap function for this like below:
$("img.fancybox-image").wrap('<a href="#" />');
Upvotes: 4
Reputation: 3760
I would use jQuery .wrap()
function for this as follow.
$( ".fancybox-image" ).wrap( "<a href='LINK_TO_NAVIGATE'></a>" );
Upvotes: 1
Reputation: 19133
Get the HTML inside the container, add the anchor tag and append it again.
jQuery(document).ready(function($) {
var html = jQuery('.fancybox-inner').html()
var newHtml = '<a href="#" class="new-img-holder">' + html + '</a>'
jQuery('.fancybox-outer').empty().html(newHtml);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="fancybox-outer">
<div class="fancybox-inner" style="overflow: visible; width: 640px; height: 463px;">
<img class="fancybox-image" src="cine-sudarshan.jpg" alt="">
</div>
</div>
Upvotes: 0
Reputation: 13678
If you just want the anchor to go before, use jQuery's .prepend
or .prependTo
methods. If you want to truly wrap it, then use jQuery's .wrap
method.
(Or, perhaps the more correct answer is Sytor's -- which is to just do it directly in your markup.)
Upvotes: 0