Skip to content

Instantly share code, notes, and snippets.

@httpsterio
Last active May 30, 2020 02:51
Show Gist options
  • Save httpsterio/0afbd0407f4787e0706538e2e73316c5 to your computer and use it in GitHub Desktop.
Save httpsterio/0afbd0407f4787e0706538e2e73316c5 to your computer and use it in GitHub Desktop.
const articleImages = [...document.querySelectorAll("main article img")];
if (articleImages.length) {
articleImages.forEach((image) => {
// If an image has a title it means that the user added a caption
// so replace the image with a figure containing that image and a caption
if (image.hasAttribute("title")) {
const figure = document.createElement("figure");
const figCaption = document.createElement("figcaption");
figCaption.innerHTML = image.getAttribute("title");
image.removeAttribute("title");
figure.appendChild(image.cloneNode(true));
figure.appendChild(figCaption);
image.replaceWith(figure);
}
image.setAttribute("loading", "lazy");
image.setAttribute("data-src", image.src);
image.removeAttribute("src");
});
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment