Skip to content

Instantly share code, notes, and snippets.

@nicordev
Last active December 24, 2018 17:05
Show Gist options
  • Save nicordev/9e680567de536248478d59c4bedcb089 to your computer and use it in GitHub Desktop.
Save nicordev/9e680567de536248478d59c4bedcb089 to your computer and use it in GitHub Desktop.
Create a DOM element if it does not exist already
/**
* Create a DOM element if it does not exist already
*
* @param {String} id the id of the element
* @param {String} eltTag HTML tag of the element
* @param {String} txtContent = '' the content of the element
* @return {DOM element} the DOM element
*/
function createOrGetElementById(id, eltTag, txtContent = '') {
var elt = document.getElementById(id);
if (elt === null) {
elt = document.createElement(eltTag);
elt.id = id;
}
if (txtContent)
elt.appendChild(document.createTextNode(txtContent));
return elt;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment