Build Your Own JavaScript DOM Library
About Lesson

Let’s add the method to add CSS class dynamically. Here we simple loop through each element and directly append to the element’s className property. (NOTE: As an exercise use classList to achieve the same functionality).

 // Add CSS class
  Q.fn.addClass = function (classes) {
    return this.each(function (el) {
      el.className += ' ' + classes;
    })
  }

Example => Step 13-> Add CSS class

Let’s do a quick test of the add CSS feature.

Q(() => {
  test("addClass", function() {
    let $li = Q("#tasks > li");
    $li.addClass("task");
    let $tasks = Q("li.task");
    assert($tasks.length == 6, ".task class added" );
  });
});
0% Complete