0

In this code "this" keyword is used in the div element in function calls parameter, so my question is that "this" keyword is used for object or global object like window, so why here we used "this" keyword whats the purpose of using this here, kindly Explain someone.

<!DOCTYPE HTML>
<html>
<body>
<link type="text/css" rel="stylesheet" href="example.css">

<div class="d1" onclick="highlight(this)">1 
    <div class="d2" onclick="highlight(this)">2
        <div class="d3" onclick="highlight(this)">3
        </div>
    </div>
</div>

<script>
function highlight(elem) {
    elem.style.backgroundColor='yellow'
    alert(elem.className)
    elem.style.backgroundColor = ''
}
</script>

</body>
</html>

3 Answers3

0

In your snippet, the purpose of this if follow: this is a reference to the current object(DOM element), in your case this refers to div clicked.

In your example, it is applied backgroundColor to all event because comes in play event bubbling and capturing.To stop this use stopPropagation method and pass event to function.

Here is solution:

function highlight(elem,event) {
    event.stopPropagation();
    elem.style.backgroundColor='red';
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<div class="d1" onclick="highlight(this,event)">1 
    <div class="d2" onclick="highlight(this,event)">2
        <div class="d3" onclick="highlight(this,event)">3
        </div>
    </div>
</div>
Mihai Alexandru-Ionut
  • 41,021
  • 10
  • 77
  • 103
0

Here this refers to the element, because it's an object.

When you're in the scope of an object (inside the constructor or in a prototype), then this holds the instance you're currently changing

Elements are objects inside javascript. They have an onclick property, which you can change to any function you like. The code above can be translated to the following:

element.onclick = function() {
    highlight(this);
};

You could obviously add the highlight function to the element like so:

HTMLDivElement.prototype.highlight = function() {
    // Stuff
};

Then you can put this.highlight() in the onclick, but that wouldn't be too clean.

Side note: If you aren't in the scope of an object, then this refers to the window object. This is because what you put on the global scope will be available inside that object. This is why you can reach everything by simply calling them or putting window. before them

Bálint
  • 3,717
  • 2
  • 13
  • 27
0

'this' keyword in onclick is simply a reference to DOM element on which onclick is sitting.
For example 'this' in the first div with class 'd1' is reference to that div - div with class 'd1'. In the second div with class 'd2', 'this' is reference to that div - div with class 'd2' and so on...