Home » Jquery » jQuery HTML : Metode css – Kode dan Contohnya

jQuery HTML : Metode css – Kode dan Contohnya

by Hanifah Nurbaeti
by Hanifah Nurbaeti

Section Artikel

Metode jQuery css()

Metode css() berfungsi untuk menyetel atau mengembalikan satu atau beberapa properti gaya untuk elemen yang dipilih.

Return Properti CSS

Untuk mengembalikan nilai properti CSS yang ditentukan, gunakan sintaks berikut:

css("propertyname");

Contoh berikut akan mengembalikan nilai warna latar belakang dari elemen yang cocok PERTAMA:

Contoh :

<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
  $("button").click(function(){
    alert("Background color = " + $("p").css("background-color"));
  });
});
</script>
</head>
<body>

<h2>INI HEADING 2</h2>

<p style="background-color:#ff0000">PARAGRAPH 1.</p>
<p style="background-color:#00ff00">PARAGRAPH 2.</p>
<p style="background-color:#0000ff">PARAGRAPH 3.</p>

<button>return background-color dari p</button>

</body>
</html>

Set Properti CSS

Untuk menyetel properti CSS tertentu, gunakan sintaks berikut:

css("propertyname","value");

Contoh berikut akan menyetel nilai warna latar belakang untuk SEMUA elemen yang cocok:

Contoh :

<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
  $("button").click(function(){
    $("p").css("background-color", "yellow");
  });
});
</script>
</head>
<body>

<h2>heading h2 </h2>

<p style="background-color:#ff0000">PARAGRAPH 1.</p>
<p style="background-color:#00ff00">PARAGRAPH 2.</p>
<p style="background-color:#0000ff">PARAGRAPH 3.</p>

<p>INI PARAGRAPH.</p>

<button>Set background-color dari  p</button>

</body>
</html>

Set Multiple Properti CSS

Untuk mengatur beberapa properti CSS, gunakan sintaks berikut:

css ({"propertyname": "value", "propertyname": "value", …});

Contoh berikut akan menetapkan warna latar belakang dan ukuran font untuk SEMUA elemen yang cocok:

Contoh :

<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
  $("button").click(function(){
    $("p").css({"background-color": "yellow", "font-size": "200%"});
  });
});
</script>
</head>
<body>

<h2>heading h2 </h2>

<p style="background-color:#ff0000">PARAGRAPH 1.</p>
<p style="background-color:#00ff00">PARAGRAPH 2.</p>
<p style="background-color:#0000ff">PARAGRAPH 3.</p>

<p>INI PARAGRAPH.</p>

<button>Set multiple styles untuk p</button>

</body>
</html>

You may also like