Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to return queryselector and queryselectorall in one function?

I am using functions get() and getall() to shorten query selector and query selector all.

const get = (target) => {document.querySelector(target)}
const getAll = (target) => {document.querySelectorAll(target)};

I wanted to fix this code as a function, so I was going to examine the element and create a function get() that return querySelectorAll if there are multiple elements of the same element and return querySelector if not.

So I made the code written below.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

 const get = (target) => {
    if (NodeList.prototype.isPrototypeOf(target)) {
      return document.querySelectorAll(target)
    } else {
      return document.querySelector(target)
    }
  }

  console.log(get('div'));

const get = (target) => {
    if(target, target.length > 1) {
      return document.querySelectorAll(target);
    }else{
      return document.querySelector(target)
    }
  }
  const get = (target) => {
    if(typeof(target) == 'object') {
      return document.querySelectorAll(target);
    }else{
      return document.querySelector(target)
    }
  } 

However, all of the above codes do not work.
Type of target is string when entering the function.

>Solution :

Simply check the length of the result of document.querySelectorAll.

const get = (target) => {
    const els = document.querySelectorAll(target);
    return els.length > 1 ? els : els[0];
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading