I want to convert jquery to lightweight js. But I get error.
Like I want to use jquery's $('#app').html('test');
var $ = function (method_name) {
return document.querySelector(method_name);
}
$.prototype.html = function (value) {
this.innerHTML = value;
};
$('#app').html('test'); // <--- .html() is not function
How to add .html() in $()?
only $('#app').innerHTML = 'test' is working
You can try do it with class:
class MyJQueryObject {
constructor(query) {
this.target = document.querySelector(query);
}
html(newHTML) {
if (typeof newHTML !== 'undefined') this.target.innerHTML = newHTML;
return this.target.innerHTML;
}
}
const $ = function (query) {
return new MyJQueryObject(query);
}
const target = $('#target');
console.log(target.html());
target.html('It was easy');
<div id="target">Change me if you can</div>
Also with class you can easily add/remove methods. And the best part that you can define html not as function but as property with the help of getters and setters. For me it is more clearly than check if you pass any argument or not. Example of usage:
class MyJQueryObject {
constructor(query) {
this.target = document.querySelector(query);
}
get html() {
return this.target.innerHTML;
}
set html(newHTML) {
this.target.innerHTML = newHTML;
}
}
const $ = function (query) {
return new MyJQueryObject(query);
}
const target = $('#target');
console.log(target.html);
target.html = 'It was easy';
<div id="target">Change me if you can</div>
Just found alternative jquery js -> CashJS.
The reason why I want to convert jquery to vanilla js is because I am concerned about fast performance and very lightweight js too. CashJS is abit faster than jQuery.