Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Beating jQuery addiction: Which jQuery methods are easily translated into pure javascript? [closed]

Being spoiled by jQuery I now include it into every project even if all I need from it is to call $("#div).hide() or $("#link").click() once.

I know that jQuery often takes care of cross-browser issues for you, but sometimes it is just a convenient wrapper for a native javascript methods.

So my question is which jQuery methods can be easily replaced by native javascript?


1 Answers

Here are some examples I use instead of jQuery methods (if I don't use jQuery):

  • $(node).css(values):

    function css(node, style) {
      if(node && node.style) {
        for(var key in style) {
            node.style[key] = style[key];
        }
      }
    }
    
  • $(node).show(): jQuery is more sophisticated here as it also can set the display value to e.g. inline.

    function show(node) {
      if(node && node.style) {
        node.style.display = "";
      }
    }
    
  • $(node).hide(): In addition, the jQuery method stores the previous display value.

    function hide(node) {
      if(node && node.style) {
        node.style.display = "none";
      }
    }
    
  • $(node).addClass(class)

    function addClass(node, cls) {
      if(node) {
        if(!node.className) {
            node.className = cls;
        }
        else if(node.className.indexOf(cls) == -1) {
            node.className = node.className + " " + cls;
        }
      }
    }
    
  • $(node).removeClass(class)

    function removeClass(node, cls) {
      if(node && node.className && node.className.indexOf(cls) >= 0) {
        var pattern = new RegExp('\\s*' + cls + '\\s*');
        node.className = node.className.replace(pattern, ' ');
      }
    }
    

These methods should be cross-browser compatible. The jQuery methods often provide more options, like removing multiple classes, or are more sophisticated.
It depends on your needs, whether you need the "advanced" functionality or not. Simpler methods might be sufficient. For example if I know that I will always have to hide div elements, this hide and show method is pretty ok.

Update:

Depending for which browser your are developing (e.g. making a Firefox extension) you can even get something close to jQuery's selector engine: document.querySelectorAll(selector)

like image 177
3 revsFelix Kling Avatar answered Sep 13 '25 18:09

3 revsFelix Kling