Selection and Manipulation Methods
The $ Object

The $ object

Create the $ object

var $ = function(selector) {
  // Return a new object with the selected elements
     return new $.fn.init(selector);
};

Add methods to the $ object

 
// Add methods to the $ object
$.fn = $.prototype = {
  // The selected elements
  elements: [],
  
  // Initialize the object
  init: function(selector) {
    // If the selector is a string, find the matching elements
    if (typeof selector === "string") {
      this.elements = document.querySelectorAll(selector);
    }
    // If the selector is an element, add it to the elements array
    else if (selector.nodeType) {
      this.elements = [selector];
    }
    // If the selector is an array-like object, convert it to an array and assign it to the elements array
    else {
      this.elements = [].slice.call(selector);
    }
  },
  
  // Add a class to the elements
  addClass: function(className) {
    this.elements.forEach(function(element) {
      element.classList.add(className);
    });
    return this;
  },
  
  // Remove a class from the elements
  removeClass: function(className) {
    this.elements.forEach(function(element) {
      element.classList.remove(className);
    });
    return this;
  },
  
  // Toggle a class on the elements
  toggleClass: function(className) {
    this.elements.forEach(function(element) {
      element.classList.toggle(className);
    });
    return this;
  },
  
  // Set the text content of the elements
  text: function(text) {
    this.elements.forEach(function(element) {
      element.textContent = text;
    });
    return this;
  }
};
 
// Set the prototype of the init function to the $ prototype
$.fn.init.prototype = $.fn;
 
// Add the $ object to the global scope
window.$ = $;