Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

100
Views
trying to create a simple selector function

I want to create a function called with a single parameter that will accept any valid CSS selector by using the querySelectorAll method.

The function should return two methods to mimic the .css and .html from jq.

I'm pulling my hair out with this one. Can anyone help? This is all I have come up with so far and can't get figure it out:

const $ = (selector) => {
    let element = document.querySelectorAll(selector);
    return {
        html: function(content) {
            element.innerHTML = content;
        }
    }
};
about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

Since you're picking up a list of nodes you need to find some way to iterate over them. Save your query to your returned object, add a new method called loop that can accept a callback and then iterate over the elements retrieved by the query with the callback provided by html and css. Note: return this means you can chain methods together like jQuery allows. It simply returns the object again.

function $(selector) {

  return {

    // Cache the query
    query: document.querySelectorAll(selector),

    // `loop` accepts a function (callback)
    // and calls it on each element in the query
    loop: function (cb) {
      this.query.forEach(el => cb(el));
    },

    // Call `loop` and for each element change the content
    html: function(content) {
      this.loop(el => el.innerHTML = content);
      return this;
    },

    // Call `loop` and for each element change the style
    css: function(prop, value) {
      this.loop(el => el.style[prop] = value);
      return this;
    }

  }

};

// Get all the divs with red class properies
$('div.red')
  .html('Updated')
  .css('background-color', 'red')
  .css('color', 'white');
<div>1</div>
<div class="red">2</div>
<div>3</div>
<div class="red">4</div>

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!