This is a simplified version of my problem.
I have two buttons, and one image. The image code is something like this
<img class="onoff" src="image.jpg">
When I press button one I want the image to be wrapped in an A tag, like
<a href="link.html"> <img class="onoff" src="image.jpg"> </a>
And when I press the other button, the A tags should be removed.
What's the easiest way of doing this with jQuery?
Anchor elements, as well as img and span elements are inline by default. If we wrap an image with an anchor element, the image becomes the anchor target. We can click the image anywhere and the link will work.
In general, you can't have an inline element, like an anchor (<a>) or span, wrap around a block level element like a division (<div>) or heading.
Solution 1. Of course you can put an IMG tag inside an A tag. There's nothing wrong with it.
To create an image link, you combine an <a> tag (i.e. link) with an <img> tag (i.e. image). You simply "wrap" the link code around the image code. If you check the code, you'll see that we've simply placed the code for an image inside the code for a normal link.
you have already many answers, but (at least before I started writing) none of them will correctly work.
They do not take into account that you should not wrap the <img>
with multiple <a>
tags. Furthermore, do not try to unwrap it if it is not wrapped! You would destroy your DOM.
This code simple does a verification before wrapping or unwrapping:
$(function(){ var wrapped = false; var original = $(".onoff"); $("#button1").click(function(){ if (!wrapped) { wrapped = true; $(".onoff").wrap("<a href=\"link.html\"></a>"); } }); $("#button2").click(function(){ if (wrapped) { wrapped = false; $(".onoff").parent().replaceWith(original); } }); });
Good luck!
To wrap the element
$(".onoff").wrap("<a href='link.html'></a>");
And to unwrap
$(".onoff").parent().replaceWith($(".onoff"));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With