JavaScript document createAttribute() Method Tutorial

In this section, we will learn what the document createAttribute() method is and how to use it in JavaScript.

What is document createAttribute() Method in JavaScript?

The document createAttribute() method is used to create a new HTML attribute in JavaScript.

For example, the `class`, and `id` are HTML attributes and using this method we can create them in JavaScript.

Note that using this method, we can only create a new attribute, but these newly created attributes are independent from any element in a page!

That means we need to use other methods to attach them to an element in a document.

For example, the setAttributeNode() method can be used to attach an attribute to an element using JavaScript, as you’ll see in the example section.

So remember, the createAttribute() method just creates a new attribute, but we need to use other methods to actually link these attributes to an element.

document createAttribute() Method Syntax:


document createAttribute() Method Parameters

The method takes one argument, and that is the name of the attribute that we want to create.

Note: the argument is of type string.

For example, if we want to create a class attribute, we use the value “class” as the argument of this method.

document createAttribute() Method Return Value

An attribute is basically an object. So when we create a new attribute using this method, the return value will be a reference to the newly created attribute.

Example: JavaScript add attribute to element

See the Pen JavaScript add attribute to element by Omid Dehghan (@odchan1) on CodePen.

How Does document createAttribute() Method Work in JavaScript?

In this example, we’ve called the createAttribute() method after a 3 seconds delay, creating a `class` attribute. Then using the `value` property of the newly created attribute, we’ve set a value for the class attribute and finally using the `setAttributeNode()` method, we’ve attached this attribute to the only <p> element in the page.

That’s why after 3 seconds delay, the size of the paragraph changed to 32px and its color to red.

Leave a Reply