Atribut kelas HTML


Contoh

Penggunaan atribut kelas dalam dokumen HTML:

<html>
<head>
<style>
h1.intro {
  color: blue;
}

p.important {
  color: green;
}
</style>
</head>
<body>

<h1 class="intro">Header 1</h1>
<p>A paragraph.</p>
<p class="important">Note that this is an important paragraph. :)</p>

</body>
</html>

Lebih banyak contoh "Coba Sendiri" di bawah ini.


Definisi dan Penggunaan

Atribut classmenentukan satu atau lebih nama kelas untuk sebuah elemen.

Atribut classini sebagian besar digunakan untuk menunjuk ke kelas dalam style sheet. Namun, itu juga dapat digunakan oleh JavaScript (melalui DOM HTML) untuk membuat perubahan pada elemen HTML dengan kelas tertentu.


Dukungan Peramban

Attribute
class Yes Yes Yes Yes Yes

Sintaksis

<element class="classname">

Nilai Atribut

Value Description
classname Specifies one or more class names for an element. To specify multiple classes, separate the class names with a space, e.g. <span class="left important">. This allows you to combine several CSS classes for one HTML element.

Naming rules:

  • Must begin with a letter A-Z or a-z
  • Can be followed by: letters (A-Za-z), digits (0-9), hyphens ("-"), and underscores ("_")

Lebih Banyak Contoh

Contoh

Tambahkan beberapa kelas ke satu elemen HTML:

<!DOCTYPE html>
<html>
<head>
<style>
h1.intro {
  color: blue;
  text-align: center;
}

.important {
  background-color: yellow;
}
</style>
</head>
<body>

<h1 class="intro important">Header 1</h1>
<p>A paragraph.</p>

</body>
</html>

Contoh

Menggunakan JavaScript untuk menambahkan warna latar belakang kuning ke elemen pertama dengan class="example" (indeks 0).

var x = document.getElementsByClassName("example");
x[0].style.backgroundColor = "yellow";

Contoh

Menggunakan JavaScript untuk menambahkan kelas "mystyle" ke elemen dengan id="myDIV":

document.getElementById("myDIV").classList.add("mystyle");

Halaman Terkait

Tutorial HTML: Atribut HTML

Tutorial CSS: Sintaks CSS

Referensi CSS: CSS .class Selector

Referensi DOM HTML: Metode getElementsByClassName() HTML DOM

Referensi HTML DOM: Properti className HTML DOM

Referensi HTML DOM: Properti classList DOM HTML

Referensi DOM HTML: Objek Gaya DOM HTML