First, we call the
document.createElement method with the tag name of the element that we want to create as a string.
Then we set the attributes of our newly created element by setting the properties of the newly created object.
Finally, we attach the element to the element that we want our element to be in as a child element by calling the
appendChild method of the element that want our element to stay inside of with our newly created element as the argument.
For instance, if we create a new
input element, we write:
const input = document.createElement('input');
to create an element with the
Then we can set the type, id, name, value, and readonly attributes of our newly created input element by writing:
input.id = 'foo-input'; input.name = 'foo'; input.value = 'bar'; input.readOnly = true;
We set the
id property to set the
id attribute of our input element.
name property sets the
name property of our element.
value sets the
value attribute of our element.
readOnly sets the
readonly attribute of our element. The case is different with this attribute. In HTML, it’s
Once we did that, we can call
appendChild on the parent element that we want our input element to be in with the
input element as the argument.
For instance, if we want the input element we created to be in the
body element, we can write:
Once we did that, we should see something like:
<input id="foo-input" name="foo" readonly="">
when we inspect the element. And ‘bar’ will be displayed on the screen inside the input box.
createElement, then we can set the properties which correspond to the HTML attribute that we want to set.
Then to display it, we call
appendChild on the parent element that we want our element to be displayed in with our newly created object as the argument.