Many front-end devs don’t know some useful JS and DOM API. Many of us happily use jQuery when the same API is available natively. Check how many of these you know:

  • Add CSS class to an element: element.classList.add('active') That is the equivalent to jQuery’s $(element).addClass('active')

    To check whether a CSS class exist on an element or not: element.classList.contains('active')

  • Removing a specific style from style attribute: element.style.removeProperty('display');

    Not every developer seems to know this API. Maybe because the internet seems to be filled with the jQuery solution: $(element).css('display', '');

  • Getting closest parent using a selector is useful within mouse/touch event handlers: event.target.closest('.box')

    Note: For IE 11 a polyfill would be needed.

    That is the equivalent to jQuery’s $(event.target).closest('.box')

  • Standard API replacement for shallow merge, like jQuery’s $.extend()? Object.assign({x: 1}, {y: 2}).

    Note: For IE 11 a polyfill would be needed.

  • Convert Array-like data structure to Array?

    Array.from(document.querySelectorAll('div'))

    Array.from(document.body.children)

    Note: For IE 11 a polyfill would be needed.

  • Finding the distance of an element from mouse cursor/touch point is useful during drag-&-drop operations:

    var rect = event.target.closest('.box').getBoundingClientRect(),
      offset = {
        left: event.pageX - rect.left,
        top: event.pageY - rect.top
      };
    

    The coordinates (e.pageX,e.pageY) and the coordinates returned by getBoundingClientRect(), both are relative to top-left of viewport (and not the document).

    So anytime you want to convert mouse/touch coordinates relative to another element, this trick will work.

  • Inner width of an element (excluding padding, scrollbar):
    function computedInt(el, prop) {
      return parseInt(getComputedStyle(el).getPropertyValue(prop), 10);
    }
    var innerWidth = element.clientWidth - computedInt(el, 'padding-left') - computedInt(el, 'padding-right');
    
  • Check if an element is in document: document.body.contains(element); However if you want to know whether an element is rendered on-screen, then checking whether it is in the document isn’t sufficient. The element could be using CSS display: none.
    function isOnScreen(el) {
      // offsetParent would be null if display 'none' is set.
      // However Chrome, IE and MS Edge returns offsetParent as null for
      // elements with position 'fixed' CSS.
      // So check whether the dimensions are zero.
      if (!el.offsetParent && !el.offsetWidth && !el.offsetHeight) {
          return false;
      }
      return true;
    }
    

    It is important to check whether an element is rendered by the browser before using certain APIs like offsetWidth, getComputedStyle(), since you won’t get expected value when element isn’t rendered.


Munawwar Firoz

Software developer, thinker, lollygagger.