<!-- Use a descriptive title, prefix it with [FIX], [FEATURE] or [ENHANCEMENT] if applicable (use only one) --> ## Description <!-- Write a detailed description of your changes/additions here --> Adding a snippet to fetch all images from within a desired element. <!-- If your PR resolves an issue, please state "Resolves #(issue number)" to help maintainers process it faster --> <!-- If you think your PR will cause breaking changes, require changes in the documentation etc, please be so kind as to explain what, where and how --> ## PR Type - [x] Snippets, Tests & Tags (new snippets, updated snippets, re-tagging of snippets, added/updated tests) - [ ] Scripts & Website & Meta (anything related to files in the [scripts folder](https://github.com/30-seconds/30-seconds-of-code/tree/master/scripts), how the repository's automated procedures work and the website) - [ ] Glossary & Secondary Features (anything related to the glossary, such as new or updated terms or other secondary features) - [ ] General, Typos, Misc. & Meta (everything else, typos, general stuff and meta files in the repository - e.g. the issue template) ## Guidelines - [x] I have read the guidelines in the [CONTRIBUTING](https://github.com/30-seconds/30-seconds-of-code/blob/master/CONTRIBUTING.md) document.
731 B
731 B
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', '...']