العودة إلى الدورة

Styling Elements: The .style Property

JavaScript: الدورة الكاملة للمبتدئين من 'الصفر إلى الاحتراف'

83. Styling Elements with JavaScript

We can directly manipulate the CSS styles of an element using the .style property.

Syntax (CamelCase)

CSS properties (which use hyphens, e.g., background-color) must be converted to camelCase when accessed via the JavaScript .style property (e.g., backgroundColor).

javascript const box = document.querySelector('.box');

// Set inline styles box.style.backgroundColor = 'teal'; box.style.width = '200px'; box.style.border = '2px solid black'; box.style.fontSize = '1.2em'; // Note the camelCase for font-size

Reading Styles

You can also read the currently set inline style:

javascript console.log(box.style.width); // 200px

Best Practice: Avoid Overusing .style

Setting styles directly in JavaScript often leads to messy, hard-to-maintain code. It is highly recommended to use CSS classes (Lesson 84) to manage styles and use JavaScript only to toggle the classes on or off.