Menu

gitpiper

getImages javascript Code Snippet in 2024

browserintermediate

Last Updated: 15 April 2024

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

  • Use Element.getElementsByTagName() to get all <img> elements inside the provided element.
  • Use Array.prototype.map() to map every src attribute of each <img> element.
  • If includeDuplicates is false, create a new Set to eliminate duplicates and return it after spreading into an array.
  • Omit the second argument, includeDuplicates, to discard duplicates by default.
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', '...']

javascript snippet similar to getImages For You in April 2024

Subscribe to our Newsletter

Subscribe to get resources directly to your inbox. You won't receive any spam! ✌️

© 2024 GitPiper. All rights reserved

Rackpiper Technology Inc

Company

About UsBlogContact

Subscribe to our Newsletter

Subscribe to get resources directly to your inbox. You won't receive any spam! ✌️