1

I have a img tag like

<img src="Mesothelioma_image_1.jpg"/>

I want to replace this tag with something like

<amp-img class="blog-image" src="Mesothelioma_image_1.jpg" width="50" height= "20" layout="responsive"></amp-img>

By keeping the same src attribute value.

gre_gor
  • 6,669
  • 9
  • 47
  • 52
Nicer
  • 63
  • 1
  • 1
  • 4

2 Answers2

1

You can use querySelector() to find the image. It would be easier if the image contains an id attribute.

Then, use createElement() to create the dom element by name amp-img.

Use setAttribute() to assign attributes to the new elements such as class, src, width, erc.

Use insertBefore() to add new element to the page and remove() to remove the old image element.

NOTE: I am selecting the old image with its src, please change it as per your need.

var oldImage = document.querySelector('img[src="Mesothelioma_image_1.jpg"]');

var newImage = document.createElement('amp-img');
newImage.setAttribute("class","blog-image");
newImage.setAttribute("src", oldImage.getAttribute('src'));
newImage.setAttribute("width","50");
newImage.setAttribute("height","20");
newImage.setAttribute("layout","responsive");
oldImage.parentNode.insertBefore(newImage, oldImage);
oldImage.parentNode.removeChild(oldImage);

console.log(document.querySelector('amp-img[src="Mesothelioma_image_1.jpg"]')); // to find the appended new image
<img src="Mesothelioma_image_1.jpg"/>
Hassan Imam
  • 21,956
  • 5
  • 41
  • 51
0

Please see below code.

You will need to access img using parent class or Id. i have did this work on a link click event, You can do this on document.ready or any other event as well.

jQuery('.clickMe').click(
function(e){
    e.preventDefault();
    var img = jQuery('.parent img').attr('src');  
    var newhtml='<amp-img class="blog-image" src="'+img+'" width="50" height= "20" layout="responsive"></amp-img>';
  // console.log('IMG: '+ img);
  
  jQuery('.parent').html(newhtml);
  
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="parent">
  <img src="https://mosthdwallpapers.com/wp-content/uploads/2016/08/Pakistan-Flag-Image-Free-Download.jpg"/>
</div>
<a class="clickMe" href="#">Click Me </a>

<amp-img class="blog-image" src="Mesothelioma_image_1.jpg" width="50" height= "20" layout="responsive"></amp-img>
Optimum Creative
  • 1,438
  • 13
  • 21
  • He does not need to access it using a parent class or id. Look at my comment on the [question](https://stackoverflow.com/questions/45057562/how-to-replace-an-img-html-tag-using-js-replace-method#comment77088423_45057562). – Jakob Pålsson Jul 12 '17 at 12:42
  • remove `.parent` from this line `var img = jQuery('.parent img').attr('src'); ` – Optimum Creative Jul 12 '17 at 12:44