The Element Object

The setAttribute() Method

Click "Add Class" to add a class attribute to the h1 element. You should see it change to red.


Here is the code:

<h1 id="myH1">The Element Object</h1>
<button onclick="myFunction1()">Add Class</button>
<script>
  function myFunction1() {
  document.getElementById("myH1").setAttribute("class", "democlass"); 
  }
</script>
  

The getAttribute() Method will return the value of an attribute

The value of the class attribute of the h2 element is:

Here is the code:

<h2 id="myH2" class="democlass">The getAttribute() Method will return the value of an attribute</h2>
<p>The value of the class attribute of the h2 element is:</p>   
<p id="getAttr"></p>
<script>
  const element = document.getElementById("myH2"); 
  let text = element.getAttribute("class"); 
  document.getElementById("getAttr").innerHTML = text;
</script>
  

Remove an Attribute from an Element

A Link: Go to Google.com

Click the button to remove the href attribute from the a element.

Here is the code:

<h2>Remove an Attribute from an Element</h2>
<a id="myAnchor" href="https://www.google.com">A Link: Go to Google.com</a>
<p id="remAttr">Click the button to remove the href attribute from the a element.</p>
<button onclick="myFunction2()">Try it</button>
<script>
  function myFunction2() {
    document.getElementById("myAnchor").removeAttribute("href"); 
}
</script>