Lessons from open-source: Convert an array-like HTML NodeList to a standard javascript array.

This page summarizes the projects mentioned and recommended in the original post on dev.to

Our great sponsors
  • SurveyJS - Open-Source JSON Form Builder to Create Dynamic Forms Right in Your App
  • InfluxDB - Power Real-Time Data Analytics at Scale
  • WorkOS - The modern identity platform for B2B SaaS
  • Next.js

    The React Framework

  • document.querySelectorAll(‘style[data-n-href]’) selects all elements with a data-n-href attribute in the document.

  • The result of this query is a NodeList, which is array-like but not a real array.
  • looseToArray is used to convert the NodeList into a real array of HTMLStyleElement.
  • So, the looseToArray function is used here to convert the NodeList obtained from document.querySelectorAll into a standard JavaScript array. The purpose of using slice.call is a common technique to convert array-like objects into arrays because the slice method can be called on array-like objects, and it returns a new array.

    If you are looking to practice next.js, checkout my website: https://tthroo.com/

    Experiment

    You can execute the following code to find out how HTML NodeList looks like after converting it to an array.

    const looseToArray = function(input) {
      return [].slice.call(input);
    };
    
    const currentStyleTags = looseToArray(
      document.querySelectorAll('.pw-post-body-paragraph')
    );
    
    console.log("document.querySelectorAll('.pw-post-body-paragraph')", 
      document.querySelectorAll('.pw-post-body-paragraph'))
    
    console.log("currentStyleTags", currentStyleTags);
    
    Enter fullscreen mode Exit fullscreen mode

    You need to change document.querySelectorAll(‘style[data-n-href]’) to the relevant DOM selector function that finds an element in the browser.

    Array-like NodeList

    Array-like NodeList

    NodeList converted to array

    NodeList converted to array

    Conclusion:

    In JavaScript, the NodeList returned by document.querySelectorAll is not a true array but rather a collection of nodes. While it looks like an array, it lacks many of the array methods and properties. The looseToArray function in nextjs source code is used to convert the NodeList into a regular array.

  • SurveyJS

    Open-Source JSON Form Builder to Create Dynamic Forms Right in Your App. With SurveyJS form UI libraries, you can build and style forms in a fully-integrated drag & drop form builder, render them in your JS app, and store form submission data in any backend, inc. PHP, ASP.NET Core, and Node.js.

    SurveyJS logo
NOTE: The number of mentions on this list indicates mentions on common posts plus user suggested alternatives. Hence, a higher number means a more popular project.

Suggest a related project

Related posts