7

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.

Pavlo
  • 35,298
  • 12
  • 72
  • 105

3 Answers3

6
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>
AmmarCSE
  • 28,122
  • 5
  • 36
  • 49
  • I am very new to programming. Why this code does not run when placed in – Hiranmoy Chatterjee Jun 02 '15 at 09:10
  • 1
    @HiranmoyChatterjee, this is because it is running before the DOM is ready. You need to place it in a DOMLoaded event. See http://stackoverflow.com/questions/799981/document-ready-equivalent-without-jquery and let me know if your still having trouble – AmmarCSE Jun 02 '15 at 09:18
  • Nice@AmmarCSE...document.addEventListener('DOMContentLoaded', function() { var blacks = document.getElementsByClassName('black'); for(var i =0; i< blacks.length; i++){ blacks[i].onclick = function(){ this.style.color = 'red'; } } }); – Hiranmoy Chatterjee Jun 02 '15 at 10:26
  • Notice that in browser `$` and `jQuery` are `window.$` and `window.jQuery`, respectively. Here is the `core.js` of jQuery (https://github.com/jquery/jquery/blob/master/src/core.js) where there is the constructor (jQuery or $). – Enrique René Sep 11 '20 at 12:38
1

There is no pure javascript equivalent of $(this) as $() returns a jQuery object.... instead you have to use pure javascript constructs to do the same like

function handler() {
    this.style.color = 'red';
}

var els = document.getElementsByClassName('');
for (var i = 0; i < els.length; i++) {
    els[i].addEventListener('click', handler, false)
}

function handler() {
  this.style.color = 'red';
}

var els = document.getElementsByClassName('black');
for (var i = 0; i < els.length; i++) {
  els[i].addEventListener('click', handler, false)
}
<div class="black">1</div>
<div class="black">2</div>
<div class="black">3</div>
<div class="black">4</div>
<div class="black">5</div>
Arun P Johny
  • 365,836
  • 60
  • 503
  • 504
0

You can set the css property like this:

this.style.color = "red";
Radonirina Maminiaina
  • 6,515
  • 4
  • 29
  • 54