Skip to content

Instantly share code, notes, and snippets.

@acerus
Created April 7, 2021 11:11
Show Gist options
  • Save acerus/35c46f14a86782c024cca7aa23660db9 to your computer and use it in GitHub Desktop.
Save acerus/35c46f14a86782c024cca7aa23660db9 to your computer and use it in GitHub Desktop.
Dynamically create elements (including nesting) in loops
function addElement( $tagName, $content, $class, $appendAfter, $returnNode = false ) {
// create a new div element
const newEl = document.createElement( $tagName );
if ( $class ) {
newEl.className = $class;
}
// and give it some content
if ( $tagName === 'img' ) {
newEl.src = $content;
} else {
const newContent = document.createTextNode( $content );
// add the text node to the newly created div
newEl.appendChild( newContent );
}
if ( $appendAfter ) {
$appendAfter.appendChild( newEl );
} else {
recipeCard.appendChild( newEl );
}
if ( $returnNode === true ) {
return newEl;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment