What is the createAttribute() method in DOM?
Overview
Often, we see that the layout or the content in some web pages changes as the user interacts with them. These interactions significantly impact user experience and attract more traffic to one's site.
We'll learn about the createAttribute() method of DOM, which enables developers to change the style of the content on their web pages and make them look more responsive. The createAttribute() function adds a new attribute with a user-specified name and returns the attribute object.
Syntax
document.createAttribute(attributeName)
Parameters
There is only a single parameter that we need to understand to use this method accordingly, which is the following:
attributeName: This field specifies the name of the attribute we want to create. The attribute name could beclass,id,href, or any of the attributes which HTML supports.
Note: This parameter is a required parameter, and we must define it in to make use of this method.
Return value
This method returns an attribute object of the type node representing the created attribute.
Example
Now that we are familiar with the syntax and the parameters of the method, let's see how can we use it with the help of a code example:
This attribute object has an attribute.value property, which helps set the attribute to some defined class followed by the setAttributeNode() method, which creates the attribute for the target HTML element.
Note: To learn more on the
classproperty and the methodsetAttributeNode(), please refer to the following links:
Explanation
The explanation which follows from the code example above is given below:
- Lines 3–9: In these lines of code, we have the
<style>tag in which we create the class,bgcolor. This class helps change the appearance of the target HTML element usingbackground-color&border-radiusproperties of CSS. - Line 13: This line of code contains an
<img>tag, which renders the Educative logo and will demonstrate the functionality ofcreateAttribute()as the user clicks on the<button>, present on line 14. - Line 14: Here we have a
<button>tag, which is listening for theonclickevent and triggers thecreateAttr()method defined in line 17. - Lines 16–23: This snippet of code encloses our
createAttr()in between the<script>tags which makes use of thecreateAttribute()in the following way: - Line 18: First, we will fetch the
<img>using DOM'sdocument.getElementsByTagName()method & store it in a variable,image. - Lines 19–20: Then, we make use of the
createAttribute()to create aclassattribute and assign the class ofbgcolorusing theattr.valueproperty. - Line 21: Finally, we make use of
setAttributeNode()property to bind the class we created using thecreateAttribute()method to theimage.
Note: To read more on
document.getElementsByTagName()method, please visit this link.
Free Resources