Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How would I write this JQuery addClass method in vanilla js

So how exactly would i write

$('div').addClass('border1');

in Vanilla javascript, like what would my add class method look like. So far what I have is,

function addClass(x,y) {
    x.className += " " + y;
}

but i know this is wrong, as the parameters are off. Im really lost.

like image 710
anaheimducks07 Avatar asked Nov 02 '14 02:11

anaheimducks07


People also ask

Can you mix jQuery and vanilla JS?

Yes, any code that you write in jQuery can also be written in vanilla JavaScript.

What does addClass do in jQuery?

The addClass() method adds one or more class names to the selected elements. This method does not remove existing class attributes, it only adds one or more class names to the class attribute. Tip: To add more than one class, separate the class names with spaces.

What is vanilla jQuery?

Vanilla JS helped the developers in creating dynamic websites. Then came jQuery, a library of tools created by developers around the world, using Javascript. In simple words, jQuery is a lightweight and easy to use JavaScript library that helps in creating complex functionalities with few lines of coding.


1 Answers

Let's take a closer look at what jQuery does here.

What is the meaning of $('div')?

In jQuery terms it means "select all 'div' elements in the document".
$('div') is a jQuery object which represents all div elements in the document. But nowhere in this code you specifically target a single DOM element by yourself.

Let's write our own simplified selection object "MySelect":

/**
 * `MySelect` object constructor.
 */
function MySelect(selector){
    this.elementList = document.querySelectorAll(selector);
}

Now let's use it:

var divs = new MySelect('div');
divs.elementList; // all `div` elements in the document.

(Note that querySelectorAll is a native javascript DOM method)

Now that we have an elements selection object, let's add an addClass method to it:

/**
 * Add the specified class to all elements selected by this object.
 */
MySelect.prototype.addClass = function(cls){
    var i, e;
    for (i = 0; i < this.elementList.length ; i++){
        e = this.elementList[i];
        e.className += " " + cls;
        // can also use e.classList.add
    }
}

And voila:

divs.addClass('xyz');

This, in a very simplified fashion, is how jQuery works.

For the $ syntax you can do:

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

And use it as usual:

$('div').addClass('xyz');
like image 190
EyalAr Avatar answered Oct 06 '22 00:10

EyalAr