Categories
HTML JavaScript

Javascript – Create an Element with Attributes

Spread the love

We can create an HTML element with JavaScript that has various attributes by calling a few methods and setting a few properties.

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 input tag.

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.

The name property sets the name property of our element.

value sets the value attribute of our element.

And readOnly sets the readonly attribute of our element. The case is different with this attribute. In HTML, it’s readonly and in JavaScript it’s readOnly.

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:

document.body.appendChild(input);

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.

We can create an element with attributes with JavaScript by first calling 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.

2 replies on “Javascript – Create an Element with Attributes”

Hi. Thank you for the instruction! It was very helpful! One question, how to tell appendChild() to create new input under existing first, second or third input element rather than body element. For example, I have a form with defined input and a button that creates new input under the first input element, if needed. Is there a special way of doing this? Hopefully, I was clear enough with the explanation 🙂

Andrius

Thanks for reading.

You can appendChild on the element that you want to attach the element to, so you know exactly how many times it’s called.

Leave a Reply

Your email address will not be published.

If you like the content of this blog, subscribe to my email list to get exclusive articles not available to anyone else.