Mengubah atribut elemen seperti src gambar, href tautan, atau disabled tombol sering dibutuhkan dalam halaman interaktif. Artikel ini membahas cara mengambil dan mengatur atribut elemen di JavaScript.
getAttribute() dan setAttribute()
<img id="foto" src="lama.jpg">
<script>
const img = document.getElementById("foto");
console.log(img.getAttribute("src")); // "lama.jpg"
img.setAttribute("src", "baru.jpg"); // ganti gambar
</script>
Contoh Kasus: Galeri Gambar (Ganti Gambar Utama)
<script>
document.querySelectorAll(".thumbnail").forEach(thumb => {
thumb.addEventListener("click", function() {
const utama = document.getElementById("utama");
utama.setAttribute("src", this.getAttribute("src"));
});
});
</script>
Menghapus Atribut
<script>
document.getElementById("tombol").removeAttribute("disabled"); // aktifkan
</script>
Properti vs Atribut
Untuk beberapa hal seperti value input atau checked checkbox, mengakses properti langsung (el.value) lebih andal daripada getAttribute().
Kesimpulan
Gunakan getAttribute()/setAttribute() untuk mengelola atribut, dan removeAttribute() untuk menghapusnya. Untuk nilai form yang berubah-ubah, akses properti langsung seperti el.value.
Referensi: untuk penjelasan lebih mendalam, kunjungi dokumentasi resmi JavaScript (MDN).

