从元素列表中替换html元素(Replace html elements from a list of elements)

编程入门 行业动态 更新时间:2024-10-20 16:16:17
元素列表中替换html元素(Replace html elements from a list of elements)

这听起来可能是个愚蠢的问题。 我在页面内有一组图像。 而这些图像没有ID但只有一个类。 我希望通过类名获取这些元素,并用不同的内容替换它们。 我该怎么做

This may sound a dumb question. I have a set of images inside a page. And these images doesnt have an ID but a class. I want to get these elements by their class names and replace each of them with different content. How should I do that.

最满意答案

以下使用vanilla 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"> 
  
 

The following using vanilla JavaScript (no jQuery) and does:

Select images in your page which have a class assigned (in this example imageClass). The document.querySelectorAll() allows you to select DOM elements using CSS3 selectors.

Change "content" for each image (src link), so yo ucan show up different images.

Click the button in the example to change "content" for images.

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

更多推荐

本文发布于:2023-07-08 20:01:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1080255.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:元素   列表中   html   list   elements

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!