30秒学会 JavaScript 片段 · 2018年10月12日

30秒学会 JavaScript 片段 – getImages

Fetches all images from within an element and puts them into an array

Use Element.prototype.getElementsByTagName() to fetch all <img> elements inside the provided element, Array.prototype.map() to map every src attribute of their respective <img> element, then create a Set to eliminate duplicates and return the array.

代码片段

const getImages = (el, includeDuplicates = false) => {
  const images = [...el.getElementsByTagName('img')].map(img => img.getAttribute('src'));
  return includeDuplicates ? images : [...new Set(images)];
};

使用样例

getImages(document, true); // ['image1.jpg', 'image2.png', 'image1.png', '...']
getImages(document, false); // ['image1.jpg', 'image2.png', '...']