Home > Back-end >  trying to create a simple jquery $ function
trying to create a simple jquery $ function

Time:10-22

I've been tasked with creating my own simplified version of jQuery:

First I have 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 an object with two methods to mimic these two methods from jQuery: .css(property, value) and .html(string)

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;
        }
    }
};

CodePudding user response:

The missing piece is that you need a loop.

const $ = (selector) => {
    const nodes = document.querySelectorAll(selector);
    return {
        css: function (property, value) {
            nodes.forEach(node => node.style[property] = value);
            return this;
        },
        html: function (string) {
            nodes.forEach(node => node.innerHTML = string);
            return this;
        }
    };
};

$("li").css("color", "red").css("font-weight", "bold");
$("p").html("<em>look ma, no hands!</em>");
<ul>
  <li>one</li>
  <li>two</li>
  <li>three</li>
</ul>
<p></p>
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

Returning this means you get a fluent interface, where you can keep calling the methods back-to-back.

CodePudding user response:

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>
<iframe name="sif2" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

  • Related