This content originally appeared on Go Make Things and was authored by Go Make Things
Today’s article is a short one.
You can use the document.createElement()
to create an element. Pass in the element to create, without angled brackets (<>
), as an argument
let div = document.createElement('div');
let link = document.createElement('a');
let article = document.createElement('article');
You can use any valid HTML tag, and even create custom ones, too. For example, these also work.
let chicken = document.createElement('chicken'); // <chicken></chicken>
let placeholder = document.createElement('_'); // <_></_>
You can manipulate an element created with document.createElement()
like you would any other element in the DOM.
Add classes, attributes, styles, and more.
let div = document.createElement('div');
div.textContent = 'Hello, world!';
div.className = 'new-div';
div.id = 'new-div';
div.setAttribute('data-div', 'new');
div.style.color = '#fff';
div.style.backgroundColor = 'rebeccapurple';
This content originally appeared on Go Make Things and was authored by Go Make Things

Go Make Things | Sciencx (2021-03-16T14:30:00+00:00) Creating a new element with vanilla JS. Retrieved from https://www.scien.cx/2021/03/16/creating-a-new-element-with-vanilla-js/
Please log in to upload a file.
There are no updates yet.
Click the Upload button above to add an update.