Skip to content

Instantly share code, notes, and snippets.

@maximumdata
Created December 22, 2016 14:13
Show Gist options
  • Save maximumdata/b9e9da675cbc98c0287e2e677c23ee1e to your computer and use it in GitHub Desktop.
Save maximumdata/b9e9da675cbc98c0287e2e677c23ee1e to your computer and use it in GitHub Desktop.
Reusable ES6 code to transform <img> DOM elements into <figures> with the image's alt text as a <figcaption>
let processImages = (selector) => {
let container = document.querySelector(selector)
let images = Array.from(container.getElementsByTagName('img'))
images.forEach((e, a, i) => {
if (!(e.getAttribute('data-processed'))) {
let fig = document.createElement('figure')
fig.innerHTML = `<img data-processed="true" src="${e.src}"><figcaption>${e.alt}</figcaption>`
e.parentNode.replaceChild(fig, e)
}
})
}
// usage:
processImages('.content')
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment