Skip to content

Instantly share code, notes, and snippets.

@OliverJAsh
Created May 3, 2017 12:37
Show Gist options
  • Save OliverJAsh/828b89816fb4dc22d582e7419012b368 to your computer and use it in GitHub Desktop.
Save OliverJAsh/828b89816fb4dc22d582e7419012b368 to your computer and use it in GitHub Desktop.
Find all usages of an image URL in the DOM (background image or img src)
const findImageUsages = url => {
const allNodes = Array.from(document.querySelectorAll('*'));
return allNodes
.map(node => {
const backgroundImageUrl = window.getComputedStyle(node).backgroundImage
// Remove `url()` or `url("")` wrapper
.slice(4, -1)
.replace(/"/g, '');
const hasMatchingBackgroundImageUrl = backgroundImageUrl === url;
const hasMatchingUrl = node.src === url;
return { node, hasMatchingBackgroundImageUrl, hasMatchingUrl };
})
.filter(item => {
return item.hasMatchingBackgroundImageUrl || item.hasMatchingUrl;
});
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment