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.
Yes, any code that you write in jQuery can also be written in vanilla JavaScript.
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.
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.
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');
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With