Encodera

Thanks for reading!

Donate to the site — we work hard for you.

Contents

Classes and styles

It is better to describe the look of elements in CSS classes and only add or remove those classes from JavaScript. jQuery has four methods for that. For the rare cases when you need a specific style value, there is the css() method.

Adding and removing a class

<style>
  .done { text-decoration: line-through; color: gray; }
</style>
 
<ul>
  <li>Buy bread</li>
  <li>Call Oleg</li>
</ul>
 
<script src="https://code.jquery.com/jquery-3.7.1.min.js"></script>
<script>
  $('li').first().addClass('done');
</script>

The first item is crossed out: it got the done class, and the style is defined in <style>. In a project the styles live in a separate file such as style.css.

The other methods work the same way:

MethodWhat it does
addClass('done')Adds the class
removeClass('done')Removes the class
toggleClass('done')Adds the class if missing, removes it if present
hasClass('done')Returns true or false

Several classes are separated by spaces: addClass('done important').

Toggling by condition

toggleClass() has a second argument: true adds the class, false removes it. This helps when the state is already known:

<style>
  .done { text-decoration: line-through; color: gray; }
</style>
 
<ul>
  <li>Buy bread</li>
  <li>Call Oleg</li>
</ul>
 
<script src="https://code.jquery.com/jquery-3.7.1.min.js"></script>
<script>
  const isDone = true;
 
  $('li').eq(1).toggleClass('done', isDone);
 
  console.log($('li').eq(1).hasClass('done')); // true
  console.log($('.done').length);              // 1
</script>

The second item is crossed out, and the output confirms the class is there.

The css method

css() reads and sets styles directly in the element's style attribute:

<p id="counter">Tasks: 3</p>
 
<script src="https://code.jquery.com/jquery-3.7.1.min.js"></script>
<script>
  $('#counter').css('font-size', 20);
  $('#counter').css({ color: 'white', backgroundColor: 'teal', padding: '4px 8px' });
 
  console.log($('#counter').css('font-size')); // 20px
</script>

jQuery adds px to numbers. Property names can be written as in CSS (font-size) or JavaScript style (backgroundColor). When reading, css() returns the computed value, the one the browser actually applied.

The same in plain JavaScript

addClass, removeClass, toggleClass, hasClass correspond to classList.add, classList.remove, classList.toggle, classList.contains. css() corresponds to element.style and getComputedStyle().

Common mistake

Putting a dot in the class name: addClass('.done'). The dot belongs only in a selector. The method adds a class literally named .done, and the style does not apply. Correct: $('.done') to find and addClass('done') to add.

Thanks for reading!

Donate to the site — we work hard for you.