简体   繁体   中英

Wrap an HTML tag in another using jQuery

http://jsfiddle.net/62w8f00o/

I have some HTML like this:

<div><img src="http://i.imgur.com/4pB78ee.png"/></div>

and I want to wrap the img tag with an a tag using jQuery, like this:

$(function() {
  var a = '<a href="http://i.imgur.com/4pB78ee.png"></a>';
  // want to wrap the <img> with the above <a> here
});

The final result would be like this:

<div>
    <a href="http://i.imgur.com/4pB78ee.png">
        <img src="http://i.imgur.com/4pB78ee.png"/>
    </a>
</div>

How can I wrap my img with the a ?

You can use the jQuery wrap function .

$( "img" ).wrap( "<a href=\"http://i.imgur.com/4pB78ee.png\"></a>" );

Replace the $( "img" ) above for the actual selector, you don't want to select all images in your webpage.

Fiddle: http://jsfiddle.net/5c5bffh1/

The syntax is:

$('.inner').wrap('<a class="outer"></a>);

So it would be something like:

$('img').wrap('<a href="http://i.imgur.com/4pB78ee.png"></a>')

Use jQuerys .wrap()

$(function() {
  var a = '<a href="http://i.imgur.com/4pB78ee.png"></a>';
  $('img').wrap(a);  
});

Updated fiddle: http://jsfiddle.net/62w8f00o/1/

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