DEV Community

Cover image for Let's create our own selector library.
Frank Wisniewski
Frank Wisniewski

Posted on

Let's create our own selector library.

The basic framework:

<!DOCTYPE html>
<html lang=de>
  <meta charset=UTF-8>
  <title>myDemo</title>
  <style>
    .blue{
      color:blue;
    }
    .pointer{
      cursor:pointer;
    }
  </style>
  <h1>Selector</h1>
  <p>lorem 1</p>
  <p>lorem 2</p>
<script> 
"use strict";
const $ = function ( selector = null ) {
  class selection {
    constructor( selector ) {    
      if ( selector ) {
        this.nodes =
         selector === document ? [document] :
         selector === window ? [window] :
         selector.nodeType ? [selector] :
         selector.constructor.name==this.constructor.name ? selector.nodes :
         NodeList.prototype.isPrototypeOf( selector ) ? selector :
         document.querySelectorAll( selector )
         this.toNode=this.nodes[0] 
      }
    }

    each = callback => ( this.nodes.
      forEach( ( _node, index ) => 
        callback( _node, index )
      ), this)

    addClass = ( ...classes ) => this
      .each( _node =>
        _node.classList.add( ...classes ) )

    removeClass = ( ...classes ) => this
      .each( _node =>
        _node.classList.remove( ...classes ) )

    click = callBack => this
      .each( ( _node ) => _node
      .addEventListener( 'click' , callBack ) )

  }
  return selector = new selection( selector )
}

$( 'p' )
  .addClass( 'blue', 'red' )
  .addClass( 'white' )
  .removeClass( 'white', 'red' )
  .click( ( el ) => console.log(
    el.currentTarget.textContent
  ))
  .addClass( 'pointer' )

</script>
Enter fullscreen mode Exit fullscreen mode

Write your suggestions and code for the extension in the comments:

Discussion (1)

Collapse
frankwisniewski profile image
Frank Wisniewski Author
// $('button').on('click', doSomething)
on = ( evt , callBack, options=null ) => this
   .each( ( _node ) => _node
   .addEventListener( evt , callBack, options ) )
Enter fullscreen mode Exit fullscreen mode