JavaScript

Applicare classi

by Andrea Spera

Esempio di utilizzo di className per applicare classi CSS ad elementi di una pagina HTML.
Codice
<!DOCTYPE html>
<html>
<head>

<script>
function classNameApply()
	{
	if(document.getElementById('divId').className == "white")
		{
		document.getElementById('divId').className = "red";
		}
		else
			{
			document.getElementById('divId').className = "white";
			}
	}
</script>

<style>
div#divId{font-size:18px;cursor:pointer;}
.red{color:red;}
.white{color:white;}
</style>

</head>
<body>

<div id="divId" class="red">Click me!</div>

<script>
document.getElementById("divId").addEventListener("click", classNameApply);
</script>

</body>
</html>
Output
Click me!