How to get the class name for a HTML element in Javascript

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.

Example


<!DOCTYPE HTML> 
<html> 
<head> 
    <style> 
        p { <!--from  www. j av a2 s.  c om-->
            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





















Home »
  Javascript »
    Javascript Reference »




Array
Canvas Context
CSSStyleDeclaration
CSSStyleSheet
Date
Document
Event
Global
History
HTMLElement
Input Element
Location
Math
Number
String
Window