Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> JavaScript

Thay đổi CSS style của element bằng JavaScript

JS thao tác style thông qua property element.style — object chứa các CSS property dạng camelCase (ví dụ: fontSize, backgroundColor).

Cách truy cập element

  • document.getElementById('id') — theo ID.
  • document.querySelector('selector') — CSS selector (khuyên dùng).
  • document.getElementsByClassName('class') — trả về HTMLCollection (live).

Ví dụ 1: Thay đổi font-size và font-style

<p id="textSize">JavaScript thay đổi font size.</p>
<p id="textStyle">JavaScript thay đổi font style.</p>
<button onclick="document.getElementById('textSize').style.fontSize='35px'">Size</button>
<button onclick="document.getElementById('textStyle').style.fontStyle='italic'">Style</button>

Ví dụ 2: Thay đổi color

<p id="textColor">JavaScript thay đổi màu chữ.</p>
<button onclick="document.getElementById('textColor').style.color='blue'">Color Me</button>

Best Practice: Dùng class thay vì inline style

Khuyên dùng: Toggle class CSS — tách biệt logic JS và presentation CSS.

CSS

.highlight { color: blue; font-weight: bold; font-size: 1.2em; }
.hidden { display: none; }

JS

<script>
  const el = document.querySelector('#myElement');
  el.classList.add('highlight');    // Thêm class
  el.classList.remove('hidden');    // Xóa class
  el.classList.toggle('active');    // Bật/tắt
  el.classList.contains('highlight'); // Kiểm tra
</script>

Lưu ý

  • Property JS dùng camelCase: font-size → fontSize, background-color → backgroundColor.
  • Inline style (element.style.xxx) có độ ưu tiên cao hơn class (trừ !important).
  • Đọc computed style: getComputedStyle(element).propertyName.
  • Để set nhiều style cùng lúc: element.style.cssText = 'color: red; font-size: 14px;'.