简体   繁体   English

如何更换 <img/> 使用JavaScript .replace()方法的HTML标签

[英]How to replace an <img/> HTML tag using JavaScript .replace() method

I have a img tag like 我有一个img标签一样

<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. 通过保持相同的src属性值。

Please see below code. 请参见下面的代码。

You will need to access img using parent class or Id. 您将需要使用父类或ID访问img。 i have did this work on a link click event, You can do this on document.ready or any other event as well. 我已经对链接单击事件进行了此项工作,也可以对document.ready或任何其他事件进行此工作。

 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> 

You can use querySelector() to find the image. 您可以使用querySelector()查找图像。 It would be easier if the image contains an id attribute. 如果图像包含id属性,会更容易。

Then, use createElement() to create the dom element by name amp-img . 然后,使用createElement()通过名称amp-img创建dom元素。

Use setAttribute() to assign attributes to the new elements such as class, src, width, erc. 使用setAttribute()将属性分配给新元素,例如class,src,width,erc。

Use insertBefore() to add new element to the page and remove() to remove the old image element. 使用insertBefore()将新元素添加到页面,并使用remove()删除旧的图像元素。

NOTE: I am selecting the old image with its src , please change it as per your need. 注意:我正在选择带有src的旧图像,请根据需要进行更改。

 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"/> 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM