I am giving a simple example of jQuery code below:
$(".black").on("click", function() {
$(this).css("color", "red");
});
When an element with 'black' css class is clicked, the particular element's (this) color turns to red.
Now, how the above code can be written in pure JavaScript? Please tell me the JavaScript equivalent of Jquery $(this) when it is used against a class selector.
“This” keyword refers to an object that is executing the current piece of code. It references the object that is executing the current function. If the function being referenced is a regular function, “this” references the global object.
In jQuery, you can listen to events for dynamically added elements using the on() function. The equivalent in JavaScript is addEventListener() function.
jQuery is a JavaScript library, so it operates on top of JavaScript. It cannot exist on its own, so you can't use one over the other. You can use just JavaScript or JavaScript and jQuery. jQuery was introduced to make development with JavaScript easier.
var blacks = document.getElementsByClassName('black');
for(var i =0; i< blacks.length; i++){
blacks[i].onclick = function(){
this.style.color = 'red';
}
}
var blacks = document.getElementsByClassName('black');
for(var i =0; i< blacks.length; i++){
blacks[i].onclick = function(){
this.style.color = 'red';
}
}
<div class="black">test</div>
<div class="black">test</div>
<div class="black">test</div>
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