[英]Replace html elements from a list of elements
這聽起來可能是一個愚蠢的問題。 我在頁面內有一組圖像。 這些圖像沒有ID而是一個類。 我想通過類名稱來獲取這些元素,並用不同的內容替換它們。 我應該怎么做。
以下使用普通JavaScript(無jQuery)執行:
在頁面中選擇已分配了類的圖像(在本示例中為imageClass
)。 document.querySelectorAll()
允許您使用CSS3選擇器選擇DOM元素。
更改每個圖像的“內容”(src鏈接),以便顯示不同的圖像。
單擊示例中的按鈕以更改圖像的“內容”。
(function() { var changeContent = function() { document.querySelectorAll('.imageClass').forEach(function(image) { image.src = 'https://placeimg.com/340/280/people' }); }; document.getElementById('btn').addEventListener('click', changeContent); })();
<button id="btn" type="button">Change Images</button> <img class="imageClass" src="https://placeimg.com/240/180/animals"> <img class="imageClass" src="https://placeimg.com/240/180/animals"> <img class="imageClass" src="https://placeimg.com/240/180/animals"> <img class="imageClass" src="https://placeimg.com/240/180/animals">
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.