attributes

In this chapter you will learn:

  1. How to use attributes property for html element

Access the attributes

You can obtain a collection containing all of the attributes. attributes property returns an array of Attr objects.

The properties of the Attr object are described in the following table.

PropertiesDescriptionReturns
nameReturns the name of the attributestring
valueGets or sets the value of the attributestring
<!DOCTYPE HTML> <!--from java  2  s  . c  o  m-->
<html> 
<body> 
 <p id="textblock" 
    class="Survey numbers" 
    data-Survey="apple" 
    data-sentiment="like"> 
     This is a test.
 </p> 
 <script> 
     var elem = document.getElementById("textblock"); 
     var attrs = elem.attributes; 
     for (var i = 0; i < attrs.length; i++) { 
         document.writeln("Name: " + 
               attrs[i].name + 
               " Value: " + 
               attrs[i].value); 
     } 
     attrs["data-Survey"].value = "banana"; 
     document.writeln("Value of data-Survey attr: " + 
                attrs["data-Survey"].value); 
 </script> 
</body> 
</html>

Click to view the demo

Next chapter...

What you will learn in the next chapter:

  1. How to get and manage the class list for a HTML element
Home » Javascript Tutorial » HTML Operation
HTMLElement
addEventListener
appendChild
attributes
classList
className
cloneNode
createElement
createTextNode
dataset
getAttribute
getElementsByTagName
hasAttribute
innerHTML
insertAdjacentHTML
insertBefore
isSameNode
outerHTML
onmouseout
onmouseover
removeEventListener