Search code examples
javascriptjqueryimagealt

How to create <span> element from img alt tag and append it after <img> line


I've some images with 'alt' tag and I want to extract 'alt' tag for every img and create a <span> + alt tag + </span> line after each img. I don't know how to do it with jQuery.

The result should be the following:

<img alt="Madrid" class="gallery__block vertical" src="1.jpg">
<span>Madrid</span>
<img alt="Paris" class="gallery__block vertical" src="2.jpg">
<span>Paris</span>
<img alt="Rome" class="gallery__block vertical" src="3.jpg">
<span>Rome</span>

Thank you very much for any help


Solution

  • So select the image, loop over, read the attribute, and insert a new element.

    $("img").each(function(){
      var img = $(this);
      var span = $("<span/>");
      span.text(img.attr("alt"));
      img.after(span);
    });
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <img alt="Madrid" class="gallery__block vertical" src="http://placekitten.com/100/100">
    <img alt="Paris" class="gallery__block vertical" src="http://placekitten.com/100/100">
    <img alt="Rome" class="gallery__block vertical" src="http://placekitten.com/100/100">