Created
September 25, 2023 21:25
-
-
Save floydnoel/56596e344d3ff65c32aae3bf1df31f5e to your computer and use it in GitHub Desktop.
Updates HTML Head tags, such as meta tags
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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