Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery: Easiest way to wrap an image tag with an A anchor tag

Tags:

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?

like image 804
cannyboy Avatar asked Nov 19 '09 23:11

cannyboy


People also ask

Can you wrap an image within an anchor element?

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.

Can you wrap a div in an a tag?

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.

Can image tag be placed inside an anchor tag?

Solution 1. Of course you can put an IMG tag inside an A tag. There's nothing wrong with it.

How do I wrap an image in a link in HTML?

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.


2 Answers

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!

like image 124
Bruno Reis Avatar answered Oct 06 '22 13:10

Bruno Reis


To wrap the element

$(".onoff").wrap("<a href='link.html'></a>"); 

And to unwrap

$(".onoff").parent().replaceWith($(".onoff")); 
like image 29
Simon Fox Avatar answered Oct 06 '22 12:10

Simon Fox