Use of Attribute in DOM

Use of Attribute in DOM

  • HTML Attributes & DOM Object’s Properties – understand the relationship between HTML attributes & DOM object’s properties.
  • setAttribute() – set the value of a specified attribute on a element.
  • getAttribute() – get the value of an attribute on an element.
  • removeAttribute() – remove an attribute from a specified element.
  • hasAttribute() – check if an element has a specified attribute or not.

HTML Attributes & DOM Object’s Properties

These help to understand the relationship between them. When the web browser loads an HTML page, it generates the corresponding DOM objects based on the DOM nodes of the document.

  Example of HTML

               <input type="text" id="username">

Above HTML element has two attributes type and id. When the web browser will generate an HTMLInputElement object then it generated HTMLInputElement object will have the corresponding properties:

  • The input.type with the value text.
  • The input.id with the value username.

Attribute methods

  • element.getAttribute(name) – get the attribute value
  • element.getAttribute(name, value) – set the value for the attribute
  • element.hasAttribute(name) – check for the existence of an attribute
  • element.removeAttribute(name) – remove the attribute

element.attributes

The element.attributes property provides collection of available attributes in an element.

Example:

<body>

            <h1>Name

            <input type=”text” id=”name”>

  <script>

        let input = document.querySelector(‘#name’);

                        console.log(input);

                        for(let attr of input.attributes) {

                                    console.log(attr.name , attr.value) ;

                        }

                        input.setAttribute(‘value’, “Enter Your Name”);

                        console.log(input.getAttribute(‘value’));

                        for(let attr of input.attributes) {

                                    console.log(attr.name , attr.value) ;

                        }

                        console.log(input.hasAttribute(‘value’));

                        console.log(input.removeAttribute(‘value’));

                        for(let attr of input.attributes) {

                                    console.log(attr.name , attr.value) ;

                        }

    </script>

</body>      

Post Your Comments & Reviews

Your email address will not be published. Required fields are marked *

*

*