Skip to content
Advertisements

DOM getAttribute()

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.


getAttribute()

The JavaScript getAttribute () property returns the value of a named attribute. Note that the HTMLElement object defines the JavaScript properties that match each of the standard HTML attributes; therefore, if you only query the value of non-standard attributes, you must use this method with HTML documents.

Syntax:

element.getAttribute(name)

name: Enter the name of the attribute to which you want to retrieve the value.


getAttribute Examples

Example 1

getAttribute  example
<body>

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

            let type = document.getElementsByTagName("INPUT")[0].getAttribute("type");
            document.getElementById("result").innerHTML = type;
        }

    </script>

</body>

Example 2

getAttribute example
<body>

    
    <button id="but" onclick="myButton()">BUTTON</button><br />
    <div id="result"></div>

    <script>

        function myButton() {
            let info = document.getElementById("but").getAttribute("onclick");
            document.getElementById("result").innerHTML = info;
        }

    </script>

</body>

Example 3

getAttribute example
<body>

    <button id="but" onclick="myButton()">BUTTON</button><br />
    <p onmousedown="onmousedownFunction()"></p>
    <div id="result"></div>

    <script>

        function myButton() {
            let info = document.getElementsByTagName("P")[0].getAttribute("onmousedown");
            document.getElementById("result").innerHTML = info;
        }

    </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: