Last active
July 1, 2024 04:42
-
-
Save Shakil-Shahadat/114956eebd1acae8ee3eff8131f65da4 to your computer and use it in GitHub Desktop.
[ Delete ] Create an Element in JavaScript
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
// Create an Element | |
let ele = document.createElement( 'div' ); // Replace 'div' with required element | |
// Insert Text | |
ele.innerText = 'Hello World!'; | |
// or | |
ele.innerHTML = 'Hello World!'; | |
// or, not recommended | |
let textNode = document.createTextNode( 'Hello World!' ); // Create a text node | |
ele.appendChild( textNode ); | |
// Set Attribute | |
ele.setAttribute( 'class', 'demoClass' ); | |
// or, not recommended | |
let att = document.createAttribute( 'class' ); // Create a 'class' attribute | |
att.value = 'demoClass'; // Set the value of the class attribute | |
ele.setAttributeNode( att ); | |
// Add an Event | |
ele.onchange = function() // Replace 'onchange' with required event | |
{ | |
} | |
// Add event listener example | |
// Insert an Element Inside the Created Element | |
ele.append( anotherElement ); // Warning: 'anotherElement' element must exist beforehand | |
// Add the Element to Another Element | |
document.querySelector( '.className' ).append( ele ); // Warning: 'className' class must exist beforehand | |
// Add the Element to the Page | |
document.body.append( ele ); | |
// Other methods for insertion: prepend, insertbefore |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
ToDo