DEV Community

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

Posted on

3 1

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:

AWS Security LIVE!

Join us for AWS Security LIVE!

Discover the future of cloud security. Tune in live for trends, tips, and solutions from AWS and AWS Partners.

Learn More

Top comments (1)

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

Sentry image

See why 4M developers consider Sentry, “not bad.”

Fixing code doesn’t have to be the worst part of your day. Learn how Sentry can help.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay