[英]How to replace an <img/> HTML tag using JavaScript .replace() method
我有一個img
標簽一樣
<img src="Mesothelioma_image_1.jpg"/>
我想用類似的東西替換這個標簽
<amp-img class="blog-image" src="Mesothelioma_image_1.jpg" width="50" height= "20" layout="responsive"></amp-img>
通過保持相同的src
屬性值。
請參見下面的代碼。
您將需要使用父類或ID訪問img。 我已經對鏈接單擊事件進行了此項工作,也可以對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>
您可以使用querySelector()
查找圖像。 如果圖像包含id屬性,會更容易。
然后,使用createElement()
通過名稱amp-img
創建dom元素。
使用setAttribute()
將屬性分配給新元素,例如class,src,width,erc。
使用insertBefore()
將新元素添加到頁面,並使用remove()
刪除舊的圖像元素。
注意:我正在選擇帶有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.