Skip to content

DOM setAttribute()

As we create HTML elements in JavaScript, we can create and delete their attributes. For this, we use the setAttribute () method to create the attribute, the removeAttribute () method to delete the attribute, the getAttribute () method to find the attribute value, and the hasAttribute () method to check the attribute.


Sets an attribute value on the specified element. If the property already exists, the value is updated; otherwise, a new attribute is added with the specified name and value.
To get the current value of an attribute, use getAttribute (); to remove an attribute, call removeAttribute ().

Note: Although it is possible to add a style attribute to an item with this method, it is recommended that you use the properties of the Style object instead for the inline style, because it does not overwrite the other CSS properties specified in it.


element.setAttribute(name , value)

name: A new feature that you want to add.
value: The value of the new property that you want to add.

setAttribute Examples

Example 1

setAttribute example

    <div id="txt">TRUECODES.ORG</div>
        let = document.getElementById("txt");
        txt.setAttribute("style", "background-color: #9e3d05; color: #ccc; font-family: verdana ");


Example 2

setAttribute Example

    <input type="text" value=""/>
    <button onclick="myAttribute();">TRANSLATE</button>
        function myAttribute() {
            document.getElementsByTagName("INPUT")[0].setAttribute("type", "button");




Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.

%d bloggers like this: