Last active
September 2, 2023 18:25
-
-
Save floydnoel/e5e8266c1c0aca5972ae34f4089d6cc3 to your computer and use it in GitHub Desktop.
HTML page meta tag setter
This file contains hidden or 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 head meta tags | |
function addMetaTag({ name, property, value }) { | |
// console.log({ name, property, value }); | |
// input checks | |
if (value === null || value === undefined) { | |
return console.error( | |
`addMetaTag received no value to set for tag: ${name ?? property}` | |
); | |
} | |
if (!name && !property) { | |
return console.error( | |
`addMetaTag received no tag name or property to set for value: ${value}` | |
); | |
} | |
// use existing tag if available, or create it | |
let tag = | |
document.querySelector(`meta[name='${name}']`) ?? | |
document.querySelector(`meta[property='${property}']`); | |
if (!tag) { | |
tag = document.createElement("meta"); | |
} | |
// set the tag attrs | |
Boolean(name) && tag.setAttribute("name", name); | |
Boolean(property) && tag.setAttribute("property", property); | |
tag.setAttribute("content", value); | |
// insert the tag | |
document.querySelector("head").appendChild(tag); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment