Skip to content

Instantly share code, notes, and snippets.

@Shakil-Shahadat
Last active December 18, 2021 01:38
Show Gist options
  • Save Shakil-Shahadat/114956eebd1acae8ee3eff8131f65da4 to your computer and use it in GitHub Desktop.
Save Shakil-Shahadat/114956eebd1acae8ee3eff8131f65da4 to your computer and use it in GitHub Desktop.
Create an Element in JavaScript
// 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
@Shakil-Shahadat
Copy link
Author

ToDo

  • Add a shorter version of this to miscellaneous.js.
  • Write an article based on this.
  • Complete this.
  • Add references.
  • onchange => eventname

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment