className

In this chapter you will learn:

  1. How to get the class name for a HTML element

Name of a class

The following code defines style for a paragraph under p.newclass in the style section. Then it sets the class name for a paragraph in Javascript code. In this way we can change or add style for a HTML element.

<!DOCTYPE HTML> <!--from   j av a  2s .  co m-->
<html> 
<head> 
    <style> 
        p { 
            border: medium double black; 
        } 
        p.newclass { 
            background-color: grey; 
            color: white; 
        } 
    </style> 
</head> 
<body> 
    <p id="textblock" class="Survey numbers"> 
        This is a test. This is a test.
        This is a test. This is a test.
        This is a test. This is a test.
    </p> 
    <button id="pressme">Press Me</button> 
    <script> 
      document.getElementById("pressme").onclick = function(e) { 
          document.getElementById("textblock").className += " newclass"; 
      }; 
    </script> 
</body> 
</html>

Click to view the demo

Next chapter...

What you will learn in the next chapter:

  1. How to clone a node
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