Bagaimana cara mengubah kelas dinamis di css?

JavaScript dibangun untuk menyediakan interaksi. Dengan gabungan JavaScript dan CSS, pengalaman pengguna dapat ditingkatkan secara signifikan. Ini termasuk efek seperti menampilkan sesuatu saat mengklik tombol. Semua ini terjadi dengan menambahkan lapisan JavaScript di atas CSS

Elemen DOM dalam JavaScript memiliki properti di dalamnya yang disebut 'classList' yang mengembalikan kelas yang dilampirkan dengan elemen itu bersama dengan beberapa metode asli lainnya

Mari kita anggap sebuah elemen dengan kelas berikut,

Menggunakan metode 'classList' bawaan, kita bisa mendapatkan banyak informasi seperti,

Kode - JavaScript

var element = document.getElementById('div');
//We have div element in 'element' variable

//Returns the number of classes
console.log(element.classList.length); //Output: 4

//Returns the value of the class attribute
console.log(element.classList.value); //Output: one two three four
_

Tapi, tidak hanya itu, kita juga bisa menambahkan atau menghapus kelas menggunakan metode bawaan, add() dan remove(). Keduanya mengharapkan nama kelas string yang akan ditambahkan dan dihapus masing-masing

element.classList.add('five');

Mari kita pahami ini dengan contoh

Kami memiliki elemen tombol, dengan mengklik yang akan menampilkan teks. Jadi, pertama, mari kita tentukan markupnya

Kode - HTML

 Show Text 

Kami memiliki elemen tombol, yang memiliki atribut onclick yang akan memicu fungsi addClass() yang telah kami definisikan di bawah ini. Elemen paragraf berisi teks

Kode - CSS

.text {
	text-align: center;
}
.hidden {
	display: none;
}
.show {
	display: block;
}
_

Dalam kode ini, kami menargetkan tiga pemilih kelas, yang semuanya untuk teks. Sekarang di. pemilih tersembunyi, kami mendefinisikan properti tampilan sebagai tidak ada, yang tidak akan menampilkan teks di halaman web. Itu. show class, yang akan kita tambahkan pada klik tombol, akan tetapi, karena tampilan. memblokir;

Kode - JavaScript

function addClass() {
	var text = document.getElementById('text');
	text.classList.remove('hidden');
	text.classList.add('show');
}

Dalam kode sederhana ini, pertama-tama kita memilih elemen teks dan kemudian dari classList-nya, hapus kelas tersembunyi, yang menyembunyikan elemen tersebut. Dan kemudian kami menambahkan acara kelas yang akan menampilkan elemen tersebut

Saya harap Anda belajar sesuatu dari artikel ini. Bagikan pemikiran Anda dan ajukan pertanyaan Anda di komentar di bawah

Model Objek CSS (CSSOM), bagian dari DOM, memaparkan antarmuka khusus yang memungkinkan manipulasi sejumlah besar informasi mengenai CSS. Awalnya didefinisikan dalam rekomendasi Gaya DOM Level 2, antarmuka ini sekarang membentuk spesifikasi, Model Objek CSS (CSSOM) yang bertujuan untuk menggantikannya

Dalam banyak kasus, dan jika memungkinkan, praktik terbaik adalah memanipulasi kelas secara dinamis melalui properti className karena tampilan akhir dari semua kait penataan dapat dikontrol dalam satu lembar gaya. Kode JavaScript seseorang juga menjadi lebih bersih karena alih-alih didedikasikan untuk detail gaya, ia dapat berfokus pada semantik keseluruhan dari setiap bagian yang dibuat atau dimanipulasi, membiarkan detail gaya yang tepat ke lembar gaya. Namun, ada kasus di mana memperoleh atau memanipulasi aturan dapat berguna (baik untuk seluruh stylesheet atau elemen individual), dan hal itu dijelaskan lebih detail di bawah ini. Perhatikan juga bahwa, seperti gaya DOM elemen individu, ketika berbicara tentang memanipulasi lembar gaya, ini sebenarnya tidak memanipulasi dokumen fisik, tetapi hanya representasi internal dari dokumen tersebut.

Objek style dasar memperlihatkan antarmuka Stylesheet dan CSSStylesheet. Antarmuka tersebut berisi anggota seperti insertRule, selectorText, dan

<!DOCTYPE html>
<html lang="en-US">
  <head>
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width" />
    <title>simple style example</title>

    <script>
      function alterStyle(elem) {
        elem.style.background = "green";
      }

      function resetStyle(elemId) {
        const elem = document.getElementById(elemId);
        elem.style.background = "white";
      }
    </script>
    <style>
      #p1 {
        border: solid blue 2px;
      }
    </style>
  </head>

  <body>
    <!-- passes a reference to the element's object as parameter 'this'. -->
    <p id="p1" onclick="alterStyle(this);">
      Click here to change background color.
    </p>

    <!-- passes the 'p1' id of another element's style to modify. -->
    <button onclick="resetStyle('p1');">Reset background color</button>
  </body>
</html>
0 untuk mengakses dan memanipulasi aturan gaya individual yang membentuk lembar gaya CSS

Untuk sampai ke objek style dari

<!DOCTYPE html>
<html lang="en-US">
  <head>
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width" />
    <title>simple style example</title>

    <script>
      function alterStyle(elem) {
        elem.style.background = "green";
      }

      function resetStyle(elemId) {
        const elem = document.getElementById(elemId);
        elem.style.background = "white";
      }
    </script>
    <style>
      #p1 {
        border: solid blue 2px;
      }
    </style>
  </head>

  <body>
    <!-- passes a reference to the element's object as parameter 'this'. -->
    <p id="p1" onclick="alterStyle(this);">
      Click here to change background color.
    </p>

    <!-- passes the 'p1' id of another element's style to modify. -->
    <button onclick="resetStyle('p1');">Reset background color</button>
  </body>
</html>
2, Anda dapat menggunakan properti
<!DOCTYPE html>
<html lang="en-US">
  <head>
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width" />
    <title>simple style example</title>

    <script>
      function alterStyle(elem) {
        elem.style.background = "green";
      }

      function resetStyle(elemId) {
        const elem = document.getElementById(elemId);
        elem.style.background = "white";
      }
    </script>
    <style>
      #p1 {
        border: solid blue 2px;
      }
    </style>
  </head>

  <body>
    <!-- passes a reference to the element's object as parameter 'this'. -->
    <p id="p1" onclick="alterStyle(this);">
      Click here to change background color.
    </p>

    <!-- passes the 'p1' id of another element's style to modify. -->
    <button onclick="resetStyle('p1');">Reset background color</button>
  </body>
</html>
3 dan mengakses objek individual berdasarkan indeks (e. g. ,
<!DOCTYPE html>
<html lang="en-US">
  <head>
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width" />
    <title>simple style example</title>

    <script>
      function alterStyle(elem) {
        elem.style.background = "green";
      }

      function resetStyle(elemId) {
        const elem = document.getElementById(elemId);
        elem.style.background = "white";
      }
    </script>
    <style>
      #p1 {
        border: solid blue 2px;
      }
    </style>
  </head>

  <body>
    <!-- passes a reference to the element's object as parameter 'this'. -->
    <p id="p1" onclick="alterStyle(this);">
      Click here to change background color.
    </p>

    <!-- passes the 'p1' id of another element's style to modify. -->
    <button onclick="resetStyle('p1');">Reset background color</button>
  </body>
</html>
_4 adalah stylesheet pertama yang ditentukan untuk dokumen, dll. )

Dalam contoh ini latar belakang halaman diatur ke merah menggunakan CSS. JavaScript kemudian mengakses properti menggunakan CSSOM dan mengubah latar belakang menjadi biru

<html lang="en">
  <head>
    <title>Modifying a stylesheet rule with CSSOM</title>
    <style>
      body {
        background-color: red;
      }
    </style>
    <script>
      const stylesheet = document.styleSheets[0];
      stylesheet.cssRules[0].style.backgroundColor = "aqua";
    </script>
  </head>
  <body>
    The stylesheet declaration for the body's background color is modified via
    JavaScript.
  </body>
</html>

Daftar properti yang tersedia di DOM dari properti style diberikan di halaman Daftar Properti CSS DOM

Untuk memodifikasi gaya ke dokumen menggunakan sintaks CSS, seseorang dapat menyisipkan aturan atau menyisipkan tag

<!DOCTYPE html>
<html lang="en-US">
  <head>
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width" />
    <title>simple style example</title>

    <script>
      function alterStyle(elem) {
        elem.style.background = "green";
      }

      function resetStyle(elemId) {
        const elem = document.getElementById(elemId);
        elem.style.background = "white";
      }
    </script>
    <style>
      #p1 {
        border: solid blue 2px;
      }
    </style>
  </head>

  <body>
    <!-- passes a reference to the element's object as parameter 'this'. -->
    <p id="p1" onclick="alterStyle(this);">
      Click here to change background color.
    </p>

    <!-- passes the 'p1' id of another element's style to modify. -->
    <button onclick="resetStyle('p1');">Reset background color</button>
  </body>
</html>
6 yang properti
<!DOCTYPE html>
<html lang="en-US">
  <head>
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width" />
    <title>simple style example</title>

    <script>
      function alterStyle(elem) {
        elem.style.background = "green";
      }

      function resetStyle(elemId) {
        const elem = document.getElementById(elemId);
        elem.style.background = "white";
      }
    </script>
    <style>
      #p1 {
        border: solid blue 2px;
      }
    </style>
  </head>

  <body>
    <!-- passes a reference to the element's object as parameter 'this'. -->
    <p id="p1" onclick="alterStyle(this);">
      Click here to change background color.
    </p>

    <!-- passes the 'p1' id of another element's style to modify. -->
    <button onclick="resetStyle('p1');">Reset background color</button>
  </body>
</html>
7 diatur ke CSS yang diinginkan

Properti elemen style (lihat juga bagian "Objek Gaya DOM" di bawah) juga dapat digunakan untuk mendapatkan dan menyetel gaya pada elemen. Namun, properti ini hanya mengembalikan atribut gaya yang telah ditetapkan sebaris (mis. g. ,

<!DOCTYPE html>
<html lang="en-US">
  <head>
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width" />
    <title>simple style example</title>

    <script>
      function alterStyle(elem) {
        elem.style.background = "green";
      }

      function resetStyle(elemId) {
        const elem = document.getElementById(elemId);
        elem.style.background = "white";
      }
    </script>
    <style>
      #p1 {
        border: solid blue 2px;
      }
    </style>
  </head>

  <body>
    <!-- passes a reference to the element's object as parameter 'this'. -->
    <p id="p1" onclick="alterStyle(this);">
      Click here to change background color.
    </p>

    <!-- passes the 'p1' id of another element's style to modify. -->
    <button onclick="resetStyle('p1');">Reset background color</button>
  </body>
</html>
_9 mengembalikan string "
<!DOCTYPE html>
<html lang="en-US">
  <head>
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width" />
    <title>Style Property Example</title>
    <link rel="StyleSheet" href="example.css" />
    <script>
      function setStyle() {
        document.getElementById("d").style.color = "orange";
      }
      function resetStyle() {
        document.getElementById("d").style.color = "black";
      }
    </script>
  </head>

  <body>
    <div id="d" class="thunder">Thunder</div>
    <button onclick="setStyle()">Click here to change text color</button>
    <button onclick="resetStyle()">Reset text color</button>
  </body>
</html>
0", atau langsung untuk elemen itu menggunakan
<!DOCTYPE html>
<html lang="en-US">
  <head>
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width" />
    <title>Style Property Example</title>
    <link rel="StyleSheet" href="example.css" />
    <script>
      function setStyle() {
        document.getElementById("d").style.color = "orange";
      }
      function resetStyle() {
        document.getElementById("d").style.color = "black";
      }
    </script>
  </head>

  <body>
    <div id="d" class="thunder">Thunder</div>
    <button onclick="setStyle()">Click here to change text color</button>
    <button onclick="resetStyle()">Reset text color</button>
  </body>
</html>
1, meskipun mungkin ada gaya lain pada elemen dari stylesheet)

Selain itu, saat Anda menyetel properti ini pada suatu elemen, Anda mengganti gaya apa pun yang telah disetel di tempat lain untuk properti khusus elemen yang Anda setel. Menetapkan properti

<!DOCTYPE html>
<html lang="en-US">
  <head>
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width" />
    <title>Style Property Example</title>
    <link rel="StyleSheet" href="example.css" />
    <script>
      function setStyle() {
        document.getElementById("d").style.color = "orange";
      }
      function resetStyle() {
        document.getElementById("d").style.color = "black";
      }
    </script>
  </head>

  <body>
    <div id="d" class="thunder">Thunder</div>
    <button onclick="setStyle()">Click here to change text color</button>
    <button onclick="resetStyle()">Reset text color</button>
  </body>
</html>
_2, misalnya, akan mengesampingkan pengaturan yang dibuat di tempat lain untuk properti
<!DOCTYPE html>
<html lang="en-US">
  <head>
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width" />
    <title>Style Property Example</title>
    <link rel="StyleSheet" href="example.css" />
    <script>
      function setStyle() {
        document.getElementById("d").style.color = "orange";
      }
      function resetStyle() {
        document.getElementById("d").style.color = "black";
      }
    </script>
  </head>

  <body>
    <div id="d" class="thunder">Thunder</div>
    <button onclick="setStyle()">Click here to change text color</button>
    <button onclick="resetStyle()">Reset text color</button>
  </body>
</html>
2 elemen tersebut di bagian kepala, atau style sheet eksternal. Namun, ini tidak akan memengaruhi deklarasi properti lainnya untuk gaya elemen tersebut, seperti padding atau margin atau font, misalnya

Untuk mengubah gaya elemen tertentu, Anda dapat mengadaptasi contoh berikut untuk elemen yang ingin Anda gaya

<!DOCTYPE html>
<html lang="en-US">
  <head>
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width" />
    <title>simple style example</title>

    <script>
      function alterStyle(elem) {
        elem.style.background = "green";
      }

      function resetStyle(elemId) {
        const elem = document.getElementById(elemId);
        elem.style.background = "white";
      }
    </script>
    <style>
      #p1 {
        border: solid blue 2px;
      }
    </style>
  </head>

  <body>
    <!-- passes a reference to the element's object as parameter 'this'. -->
    <p id="p1" onclick="alterStyle(this);">
      Click here to change background color.
    </p>

    <!-- passes the 'p1' id of another element's style to modify. -->
    <button onclick="resetStyle('p1');">Reset background color</button>
  </body>
</html>
_

Metode

<!DOCTYPE html>
<html lang="en-US">
  <head>
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width" />
    <title>Style Property Example</title>
    <link rel="StyleSheet" href="example.css" />
    <script>
      function setStyle() {
        document.getElementById("d").style.color = "orange";
      }
      function resetStyle() {
        document.getElementById("d").style.color = "black";
      }
    </script>
  </head>

  <body>
    <div id="d" class="thunder">Thunder</div>
    <button onclick="setStyle()">Click here to change text color</button>
    <button onclick="resetStyle()">Reset text color</button>
  </body>
</html>
_4 pada objek
<!DOCTYPE html>
<html lang="en-US">
  <head>
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width" />
    <title>Style Property Example</title>
    <link rel="StyleSheet" href="example.css" />
    <script>
      function setStyle() {
        document.getElementById("d").style.color = "orange";
      }
      function resetStyle() {
        document.getElementById("d").style.color = "black";
      }
    </script>
  </head>

  <body>
    <div id="d" class="thunder">Thunder</div>
    <button onclick="setStyle()">Click here to change text color</button>
    <button onclick="resetStyle()">Reset text color</button>
  </body>
</html>
5 mengembalikan semua gaya yang sebenarnya telah dihitung untuk sebuah elemen

Objek style mewakili pernyataan gaya individual. Objek gaya diakses dari

<!DOCTYPE html>
<html lang="en-US">
  <head>
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width" />
    <title>simple style example</title>

    <script>
      function alterStyle(elem) {
        elem.style.background = "green";
      }

      function resetStyle(elemId) {
        const elem = document.getElementById(elemId);
        elem.style.background = "white";
      }
    </script>
    <style>
      #p1 {
        border: solid blue 2px;
      }
    </style>
  </head>

  <body>
    <!-- passes a reference to the element's object as parameter 'this'. -->
    <p id="p1" onclick="alterStyle(this);">
      Click here to change background color.
    </p>

    <!-- passes the 'p1' id of another element's style to modify. -->
    <button onclick="resetStyle('p1');">Reset background color</button>
  </body>
</html>
_2 atau dari elemen yang menerapkan gaya tersebut. Ini mewakili gaya in-line pada elemen tertentu

Lebih penting dari dua properti yang disebutkan di sini adalah penggunaan objek style untuk menyetel properti gaya individu pada elemen

<!DOCTYPE html>
<html lang="en-US">
  <head>
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width" />
    <title>Style Property Example</title>
    <link rel="StyleSheet" href="example.css" />
    <script>
      function setStyle() {
        document.getElementById("d").style.color = "orange";
      }
      function resetStyle() {
        document.getElementById("d").style.color = "black";
      }
    </script>
  </head>

  <body>
    <div id="d" class="thunder">Thunder</div>
    <button onclick="setStyle()">Click here to change text color</button>
    <button onclick="resetStyle()">Reset text color</button>
  </body>
</html>

Media dan jenis gaya dapat diberikan atau tidak

Perhatikan bahwa Anda juga dapat mengubah gaya elemen dengan mendapatkan referensi ke sana dan kemudian menggunakan metode

<!DOCTYPE html>
<html lang="en-US">
  <head>
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width" />
    <title>Style Property Example</title>
    <link rel="StyleSheet" href="example.css" />
    <script>
      function setStyle() {
        document.getElementById("d").style.color = "orange";
      }
      function resetStyle() {
        document.getElementById("d").style.color = "black";
      }
    </script>
  </head>

  <body>
    <div id="d" class="thunder">Thunder</div>
    <button onclick="setStyle()">Click here to change text color</button>
    <button onclick="resetStyle()">Reset text color</button>
  </body>
</html>
9 untuk menentukan properti CSS dan nilainya

const el = document.getElementById('some-element');
el.setAttribute('style', 'background-color:darkblue;');

Ketahuilah, bagaimanapun, bahwa

<!DOCTYPE html>
<html lang="en-US">
  <head>
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width" />
    <title>Style Property Example</title>
    <link rel="StyleSheet" href="example.css" />
    <script>
      function setStyle() {
        document.getElementById("d").style.color = "orange";
      }
      function resetStyle() {
        document.getElementById("d").style.color = "black";
      }
    </script>
  </head>

  <body>
    <div id="d" class="thunder">Thunder</div>
    <button onclick="setStyle()">Click here to change text color</button>
    <button onclick="resetStyle()">Reset text color</button>
  </body>
</html>
_9 menghapus semua properti style lainnya yang mungkin sudah ditentukan dalam objek style elemen. Jika
const el = document.getElementById('some-element');
el.setAttribute('style', 'background-color:darkblue;');
_3 elemen di atas memiliki atribut style in-line katakanlah
const el = document.getElementById('some-element');
el.setAttribute('style', 'background-color:darkblue;');
5, nilai itu akan dihapus dengan menggunakan
<!DOCTYPE html>
<html lang="en-US">
  <head>
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width" />
    <title>Style Property Example</title>
    <link rel="StyleSheet" href="example.css" />
    <script>
      function setStyle() {
        document.getElementById("d").style.color = "orange";
      }
      function resetStyle() {
        document.getElementById("d").style.color = "black";
      }
    </script>
  </head>

  <body>
    <div id="d" class="thunder">Thunder</div>
    <button onclick="setStyle()">Click here to change text color</button>
    <button onclick="resetStyle()">Reset text color</button>
  </body>
</html>
9

Bagaimana cara mengubah kelas CSS secara dinamis?

Dalam artikel ini, kita akan melihat cara membuat kelas CSS secara dinamis dan menerapkannya ke elemen secara dinamis menggunakan JavaScript. Untuk melakukannya, pertama-tama, kita membuat kelas dan menetapkannya ke elemen HTML tempat kita ingin menerapkan properti CSS . Kita bisa menggunakan properti className dan classList di JavaScript.

Bagaimana Anda memperbarui kelas di CSS?

Modifikasi Kelas CSS .
add() digunakan untuk menambahkan nilai kelas
toggle() digunakan untuk menghidupkan atau mematikan kelas
replace() digunakan untuk mengganti nilai kelas dengan nilai kelas lain
berisi () digunakan untuk memeriksa apakah suatu nilai ada atau tidak
remove() digunakan untuk menghapus nilai kelas

Bagaimana cara menghapus kelas dinamis di CSS?

Cara menambah/menghapus kelas CSS secara dinamis di jQuery .
$('#para1'). addClass('sorot');
$('#para1'). hapusKelas('sorot');

Bagaimana cara mengubah kelas secara dinamis di js?

Tambahkan kelas CSS secara dinamis dengan JavaScript .
Kode - JavaScript. elemen var = dokumen. .
Code - HTML. .
Kode - CSS. . .
Kode - JavaScript. fungsi addClass() { var teks = dokumen