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.

Leave a Reply

Your email address will not be published. Required fields are marked *