1

I've notice that window.$ or $ can be used without using jQuery. Is this already built in browsers? Why don't I see documentations about it?

I would like to add/create something like jQuery does without using jQuery at all. Like

$(selector).slide = function(){ //something};

How do I accomplish this without the use of jQuery? Is there a way to override window.$ or create an instance perhaps?

I know how to use jQuery btw, just wanted to make something very simple and light.

Ben Sat
  • 791
  • 1
  • 5
  • 9

1 Answers1

1

It is the same of document.querySelector if jQuery is not used :

$(SELECTOR);
// are same if jQuery is not used
document.querySelector(SELECTOR);

note that document.querySelector returns the first HTMLElement which satisfies the SELECTOR.

IF you want to get all elements , use document.querySelectorAll instead which is $$

$$(SELECTOR); // double dollar
// are same if jQuery is not used
document.querySelectorAll(SELECTOR);

Firefox :

enter image description here

Chrome :

enter image description here


PART 2 of question : Build something like jQuery :

The below example is a Proof Of Concept which handles only the first selected element .

function $(selector){
  return new MyQuery(selector);
}

class MyQuery {
    constructor(selector) {
      this.element = document.querySelector(selector);
    }
     
    html() {
      if (! arguments.length )
        return this.element.innerHTML;
      else {
         this.element.innerHTML = arguments[0];
         return this; // !! important for call chaining
      }
    }
}


//-then -- Use it : 
console.log(
  $('section').html()
);

setTimeout(() => {
   $('section').html(' I am changed by MyQuery');
   console.log(
     $('section').html()
   );
}, 2500);
<section>I want to be extracted by MyQuery</section>
Abdennour TOUMI
  • 87,526
  • 38
  • 249
  • 254