Skip to content

Instantly share code, notes, and snippets.

@floydnoel
Created September 25, 2023 21:25
Show Gist options
  • Save floydnoel/56596e344d3ff65c32aae3bf1df31f5e to your computer and use it in GitHub Desktop.
Save floydnoel/56596e344d3ff65c32aae3bf1df31f5e to your computer and use it in GitHub Desktop.
Updates HTML Head tags, such as meta tags
// update a head tag
function updateHeadTag({ tag = "meta", ...attrs }) {
// input check
const attrKeys = Object.keys(attrs);
if (attrKeys.length < 1) {
return console.error(
`updateHeadTag() received no attributes to set for ${tag} tag`
);
}
// use existing tag if available, or create it
let tagToUpdate = null;
// iterate to find the first match (excluding the content attribute)
for (let i = 0; i < attrKeys.length; i++) {
if (attrKeys[i] !== "content") {
tagToUpdate = document.querySelector(
`${tag}[${attrKeys[i]}='${attrs[attrKeys[i]]}']`
);
}
if (tagToUpdate) break;
}
// if no matching tag is found, create a new one
if (!tagToUpdate) {
tagToUpdate = document.createElement(tag);
}
// set the tag attrs
Object.keys(attrs).forEach((attr) =>
tagToUpdate.setAttribute(attr, attrs[attr])
);
// append the tag
document.querySelector("head").appendChild(tagToUpdate);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment