Skip to content
Advertisements

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.


setAttribute()

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.

Syntax:

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
<body>

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

</body>

Example 2

setAttribute Example
<body>

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

    </script>

</body>
Advertisements

4 Comments »

Leave a Reply

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

WordPress.com Logo

You are commenting using your WordPress.com 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: