Reputation: 73
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.
Upvotes: 1
Views: 1537
Reputation: 22574
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"/>
Upvotes: 1
Reputation: 1428
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>
Upvotes: 0