Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pure JavaScript equivalent of JQuery $(this)

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.

like image 601
Hiranmoy Chatterjee Avatar asked Jun 02 '15 08:06

Hiranmoy Chatterjee


People also ask

What is $( this in JavaScript?

“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.

What is the equivalent of on in jQuery to JavaScript?

In jQuery, you can listen to events for dynamically added elements using the on() function. The equivalent in JavaScript is addEventListener() function.

Can I use JavaScript instead of jQuery?

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.


1 Answers

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>
like image 79
AmmarCSE Avatar answered Sep 28 '22 06:09

AmmarCSE