JavaScript สามารถเปลี่ยน CSS styles เช่น สี, ขนาดฟอนต์ ของ elements ด้วยเมธอดอย่าง getElementById(), getElementsByClassName() เป็นต้น
ตัวอย่างเปลี่ยน font style และ font size ด้วย getElementById()
ตัวอย่างที่ 1 - เปลี่ยน Font Size และ Font Style
ใช้ style.fontSize และ style.fontStyle เปลี่ยนขนาดเป็น "35px" และ style เป็น "italic"
<html> <body>
<p id="size">JavaScript can change the style of an HTML element.</p>
<p id="style">JavaScript can change the style of an HTML element.</p>
<button type="button" onclick="document.getElementById('size').style.fontSize='35px'">Size</button>
<button type="button" onclick="document.getElementById('style').style.fontStyle='italic'">Style</button>
</body> </html>
หลังรันโค้ดจะแสดงดังภาพ

หลังกดปุ่ม ข้อความแรกเปลี่ยน font size ข้อความที่สองเปลี่ยน font style
ผลลัพธ์

ตัวอย่างที่ 2 - เปลี่ยนสีข้อความ
ใช้ style.color เปลี่ยนสีเป็นน้ำเงิน
<html> <body>
<p id="color">JavaScript can change the color of an HTML element.</p>
<button type="button" onclick="document.getElementById('color').style.color='blue'">Color Me</button>
</body> </html>
หลังรันจะแสดงดังภาพ

กดปุ่ม "Color Me" ข้อความจะเปลี่ยนสีเป็น น้ำเงิน
ผลลัพธ์
