skip to Main Content

there are several images on a page like this

<img src="https://images4.imagebam.com/qwert.jpg" alt="" />
<img src="https://images4.imagebam.com/werty.jpg" alt="" />

how to use JQuery to change these images to links to these images and add an alt to each image as shown below

<a href="https://images4.imagebam.com/qwert.jpg"><img src="https://images4.imagebam.com/qwert.jpg" alt="image1" /></a>
<a href="https://images4.imagebam.com/werty.jpg"><img src="https://images4.imagebam.com/werty.jpg" alt="image2" /></a>

There is code that does the opposite, but I can’t change it

$("a").each(function() {
  $(this).replaceWith("<img src='" + $(this).attr("href") + "'>")
})

2

Answers


  1. You’re just need to reverse the tags in the jQuery. And instead of href get src of image.

    $("img").each(function() {
      $(this).replaceWith("<a href='" + $(this).attr("src") + "'><img src='" + $(this).attr("src") + "'></a>")
    })
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.7.1/jquery.min.js"></script>
    
    <img src="https://placehold.co/200" alt="image1" />
    <img src="https://placehold.co/200" alt="image2" />
    Login or Signup to reply.
  2. Solution :
    I had already done a similar action for a website, you can modify your code like this.

    $("img").each(function(index) {
        var imgSrc = $(this).attr("src");
        var altText = "image" + (index + 1); 
    
        $(this).replaceWith(
          $("<a>")
            .attr("href", imgSrc)
            .append(
              $("<img>")
                .attr("src", imgSrc)
                .attr("alt", altText)
            )
        );
    });
    

    This code will allow you to modify all the images that it detects in the code.

    Results :
    You should get the results as requested.

    From

    <img src="https://images4.imagebam.com/qwert.jpg" alt="" />
    <img src="https://images4.imagebam.com/werty.jpg" alt="" />
    

    to

    <a href="https://images4.imagebam.com/qwert.jpg"><img src="https://images4.imagebam.com/qwert.jpg" alt="image1" /></a>
    <a href="https://images4.imagebam.com/werty.jpg"><img src="https://images4.imagebam.com/werty.jpg" alt="image2" /></a>
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search