DEV Community

bradhuang9999
bradhuang9999

Posted on

tourgroup-js: traverse Dom natively in chain

In Beta, feel free to suggest improvements.

Introduction

In the past, different browsers supported standard syntax differently. To create websites that work across platforms, we had to consider these differences. We used tricks or libraries like jQuery to solve this problem. But now, modern browsers support most standard syntax, so we don't need to worry about it. As suggested by You may not need jQuery, we can achieve the same effects using native syntax. However, native syntax can be cumbersome, so we need tools like tourgroup-js.

Native syntax is fastest, but it's complex and doesn't support chaining. jQuery supports chaining, but it doesn't support ES Modules and can cause global pollution. tourgroup-js aims to be as close to native syntax as possible while supporting chaining and ES Modules without global pollution.

For more information, visit the GitHub repository.

Demo

Online demo

Why TourGroup

  • Lightweight: Less than 10KB.
  • Fast: invoke native function directly
  • Supports ES module.
  • Browser-native interface reduces learning curve.
  • Extends Array, providing native array-related functions.
  • Chainable interface for ease of use.

Example Code

import TourGroup from 'https://cdn.jsdelivr.net/npm/tourgroup-js@1.0.0/dist/tourgroup.esm.min.js';
var tourGroup = TourGroup.at('.class1')
                         .querySelectorAll('span.class2')
                         .has('i');
tourGroup.setAttribute('data-my-attr', 'true')
         .addEventListener('click', () => {console.log('clicked')});
Enter fullscreen mode Exit fullscreen mode

Compare with jQuery

  • Not support ES Module, need to include jQuery library from HTML first.
  • Cause polution to global scope.
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
Enter fullscreen mode Exit fullscreen mode
  • function interface is different from native
  • implementation is more complex than native
var target = $('div.class1').find('span.class2').has('i');
target.attr('data-my-attr', 'true')
      .on('click', () => {console.log('clicked')});
Enter fullscreen mode Exit fullscreen mode

Compare with Native

  • Native is not chainable.
  • Without some useful functions, such as toogleClass, addDelegateEventListener, etc.
var target = document.querySelectorAll('div.class1');
for(let div of target){
  let spans = div.querySelectorAll('span.class2');
  for(let span of spans){
    if(span.querySelector('i')){
      span.setAttribute('data-my-attr', 'true');
      span.addEventListener('click', () => {console.log('clicked')});
    }
  }
}
Enter fullscreen mode Exit fullscreen mode

Top comments (0)