Created
April 7, 2021 11:11
-
-
Save acerus/35c46f14a86782c024cca7aa23660db9 to your computer and use it in GitHub Desktop.
Dynamically create elements (including nesting) in loops
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
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