JavaScript / jQuery CSS Styles

Managing CSS styles is a crucial part of creating visually appealing and dynamic web applications. Both JavaScript and jQuery provide mechanisms to get, set, and manipulate CSS properties of HTML elements.

Applying CSS Styles with JavaScript

Inline Styles

JavaScript allows you to set inline styles directly on an element.

  • Set a Single Style:
let element = document.getElementById('myElement');
element.style.color = 'blue';
  • Set Multiple Styles:
element.style.cssText = 'color: blue; font-size: 18px;';
  • Get a Style Property:
let color = window.getComputedStyle(element).color;

Adding/Removing CSS Classes

  • Add a Class:
element.classList.add('newClass');
  • Remove a Class:
element.classList.remove('oldClass');
  • Toggle a Class:
element.classList.toggle('toggleClass');

Applying CSS Styles with jQuery

jQuery simplifies working with CSS by offering chainable methods and concise syntax.

Manipulating Inline Styles

  • Set a Single Style:
$('#myElement').css('color', 'blue');
  • Set Multiple Styles:
$('#myElement').css({
  'color': 'blue',
  'font-size': '18px'
});
  • Get a Style Property:
let color = $('#myElement').css('color');

Adding/Removing CSS Classes

  • Add a Class:
$('#myElement').addClass('newClass');
  • Remove a Class:
$('#myElement').removeClass('oldClass');
  • Toggle a Class:
$('#myElement').toggleClass('toggleClass');

Dynamic Style Application Example

Using JavaScript:

let box = document.getElementById('box');
box.style.backgroundColor = 'lightblue';
box.classList.add('rounded-corner');

Using jQuery:

$('#box').css('background-color', 'lightblue').addClass('rounded-corner');

Key Differences

AspectJavaScriptjQuery
SyntaxVerboseConcise and chainable
Ease of UseMore manual stepsSimplified for developers
PerformanceSlightly faster for complex operationsSlower due to abstraction

When to Use JavaScript or jQuery for CSS

  • JavaScript: Best for performance-critical tasks or when working in environments where jQuery is unavailable.
  • jQuery: Ideal for rapid development, cross-browser compatibility, and when using other jQuery features.

For more development tips and tutorials, visit The Coding College.

Leave a Comment