Append Anchor Tag

In my application, I want to make an image a link to another page. Image is placed in html as,

<div class="rightbuttoncontainers_footer">
  <div class="forfooterimg" id="twitterlink_indv">
    <img src="Images/tweatus.png" width="30" height="30" alt="tweat">
  </div>
</div>

I want to make those image as links via script, I tried the following

var twit_lk='
$('#twitterlink_indv').append('<a href="'+twit_lk+'"/>');

But the output of the above code is like this,

<div class="rightbuttoncontainers_footer">
  <div class="forfooterimg" id="twitterlink_indv">
    <img src="Images/tweatus.png" width="30" height="30" alt="tweat">
    <a href=""></a>
  </div>
</div>

But, I want the output like the following,

<div class="rightbuttoncontainers_footer">
  <div class="forfooterimg" id="twitterlink_indv">
    <a href="">
      <img src="Images/tweatus.png" width="30" height="30" alt="tweat">
    </a>
  </div>
</div>

How can I make it work?

Please help,

Thanks

8 Answers

Have a look at .wrap() method documented here.

$('#twitterlink_indv img').wrap('<a href="' + twit_lk + '" />');  

Use the wrap method. Select the image element and wrap the link around it:

$('#twitterlink_indv img').wrap('<a href="'+twit_lk+'"></a>');

Use .wrap() , like this:

$('#twitterlink_indv img').wrap('<a href="'+twit_lk+'"/>');

try:

$('#twitterlink_indv img').wrap(
    $("<a/>").attr("href", twit_lk));
0

try using wrap instead of append like this:

$('#twitterlink_indv img').wrap('<a href="'+twit_lk+'"/>');
0

What I think you are looking for is the jQuery wrap() function.

Wrap an HTML structure around each element in the set of matched elements.

$('#twitterlink_indv > img').wrap('<a href="' + twit_lk + '" />');                   

Your selector should be altered to match the inner <img> tag. The wrap function will then wrap the matched elements with an anchor tag.

Take a look here for a demo.

References -

use jquery wrap():

$('#twitterlink_indv > img').wrap('<a href="'+twit_lk+'"/>');
0

Just use the wrapInner() method:

$('#twitterlink_indv').wrapInner('<a href="'+twit_lk+'"/>');

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Elena Rostova

Elena Rostova

Lead Health, Wellness & Medical Journalist

Elena Rostova holds a Master's degree in Public Health Journalism. She covers groundbreaking medical research, holistic wellness trends, mental health awareness, and nutritional science.

Share this article
Twitter Facebook Pinterest