0

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;
        }
    }
};
  • `element.innerHTML` makes no sense there, you do not have a direct reference to a single element there. You need to loop over the elements. https://stackoverflow.com/questions/10693845/what-do-queryselectorall-and-getelementsby-methods-return – CBroe Oct 22 '21 at 08:45
  • You need to read the documentation on the Js functions you're using https://developer.mozilla.org/en-US/docs/Web/API/Document/querySelectorAll – Liam Oct 22 '21 at 08:49

1 Answers1

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>
Andy
  • 61,948
  • 13
  • 68
  • 95