Skip to content

Instantly share code, notes, and snippets.

@floydnoel
Last active September 2, 2023 18:25
Show Gist options
  • Save floydnoel/e5e8266c1c0aca5972ae34f4089d6cc3 to your computer and use it in GitHub Desktop.
Save floydnoel/e5e8266c1c0aca5972ae34f4089d6cc3 to your computer and use it in GitHub Desktop.
HTML page meta tag setter
// 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