In the case you are asking about, this represents the HTML DOM element.

So it would be the <a> element that was clicked on.

Answer from TM. on Stack Overflow
🌐
W3Schools
w3schools.com › jsref › event_onclick.asp
onclick Event
Well organized and easy to understand Web building tutorials with lots of examples of how to use HTML, CSS, JavaScript, SQL, Python, PHP, Bootstrap, Java, XML and more.
🌐
MDN Web Docs
developer.mozilla.org › en-US › docs › Web › API › Element › click_event
Element: click event - Web APIs | MDN
addEventListener("click", (event) => { }) onclick = (event) => { } A PointerEvent. Inherits from MouseEvent. Note: In earlier versions of the specification, the event type for this event was a MouseEvent. Check browser compatibility for more information. This interface inherits properties from ...
🌐
QuirksMode
quirksmode.org › js › this.html
Javascript - The this keyword
Each time the function is called, this refers to the HTML element that is currently handling the event, the HTML element that "owns" the copy of doSomething(). ... you do not copy the function! Instead, you refer to it, and the difference is crucial. The onclick property does not contain the actual function, but merely a function call:
🌐
GeeksforGeeks
geeksforgeeks.org › javascript › javascript-onclick-event
JavaScript onclick Event - GeeksforGeeks
August 8, 2025 - There is a in-bulit method addEventListener() provided by JavaScript to attach events with the HTML elements. It takes the name of the event and the callback function as arguements to attach them. selectedHTMLElement.addEventListener('eventName', callbackFunction); Example: The below code implements the addEventListener() method to applying the onclick function.
🌐
freeCodeCamp
freecodecamp.org › news › html-button-onclick-javascript-click-event-tutorial
HTML Button onclick – JavaScript Click Event Tutorial
August 16, 2021 - We do this by assigning it a class of open in the else block, which makes it show the rest of the article. Then we set the class to an empty string (none) in the if block, which makes it return to the initial state. Our code is working fine with a smooth transition: We can separate the HTML and JavaScript and still use onclick, because onclick is JavaScript.
Find elsewhere
🌐
Tabnine
tabnine.com › home › how to use the onclick dom event with javascript
How to Use the onclick DOM Event with JavaScript - Tabnine
July 25, 2024 - The code above adds an event listener to myButton, which stores a reference to the element that we wish to receive events on. With this action, the button object is now “listening” – waiting to “hear” a click on that specific button – and will invoke the greet method when that event occurs. ... Note: the event above is defined as ‘click’, not ‘onclick’!
🌐
W3Schools
w3schools.com › tags › ev_onclick.asp
HTML onclick Event Attribute
HTML DOM reference: onclick event ❮ HTML Event Attributes ... If you want to use W3Schools services as an educational institution, team or enterprise, send us an e-mail: [email protected] · If you want to report an error, or if you want to make a suggestion, send us an e-mail: [email protected] · HTML Tutorial CSS Tutorial JavaScript Tutorial How To Tutorial SQL Tutorial Python Tutorial W3.CSS Tutorial Bootstrap Tutorial PHP Tutorial Java Tutorial C++ Tutorial jQuery Tutorial
🌐
Nickmccullum
nickmccullum.com › javascript-onclick-events
How to Use JavaScript onclick Events | Nick McCullum
You can use the onclick() event, which is a very popular event in JavaScript. It allows you to execute code when a user clicks an element on a webpage (such as a button). In this article, I will teach you how to use JavaScript onclick events to make your webpages more interactive.
🌐
Codedamn
codedamn.com › news › javascript
onclick function in Javascript- full guide 2022
September 21, 2022 - In HTML: <element onclick=”myScript”> In JavaScript: object.
🌐
Career Karma
careerkarma.com › blog › javascript › javascript onclick: a step-by-step guide
JavaScript Onclick: A Step-By-Step Guide | Career Karma
December 1, 2023 - The JavaScript onclick event executes a function when you click on a button or another web element. For instance, an onclick event can trigger a dialog box to appear when you clock on a button.
🌐
Javatpoint
javatpoint.com › javascript-onclick-event
JavaScript onclick event - javatpoint
JavaScript onload In JavaScript, this event can apply to launch a particular function when the page is fully displayed. It can also be used to verify the type and version of the visitor's browser. We can check what cookies a page uses by using the onload attribute.
Top answer
1 of 2
2

The reason is this refers to the global Window object inside the function.

You have to pass this to the function so that you can refer that inside the function:

.active{
  color:green;
  font-size: 20px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="class1" onClick="TestFunction(this);">Click</div>

<script>
function TestFunction(el) {
  console.log(this.constructor.name) //Window
  $(el).addClass('active');
}
</script>

Though it is better to avoid inline event handler:

$('.class1').click(function(){
  $(this).addClass('active');
});
.active{
  color:green;
  font-size: 20px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="class1">Click</div>
2 of 2
0

When using an inline handler the function invoked runs under the scope of the window element, not the element which raised the event. To work around that you can pass this as an argument:

<div class="class1" onClick="TestFunction(this);">Click</div>
function TestFunction(el) {
  el.addClass('active');
}

However this is not good practice. Inline event attributes are outdated and now considered bad practice. The better way to achieve this is to attach unobtrusive event handlers. In plain JS it would look like this:

<div class="class1">Click</div>
document.querySelectorAll('.class1').forEach(el => {
  el.addEventListener('click', function() {
    this.classList.add('active');
  });
});

In jQuery it would look like this:

<div class="class1">Click</div>
jQuery($ => {
  $('.class1').on('click', function() {
    $(this).addClass('active');
  });
});
🌐
SitePoint
sitepoint.com › javascript
Getting source element of onclick event - JavaScript - SitePoint Forums | Web Development & Design Community
June 6, 2007 - I’m trying to add an onclick of a link and, in the handler function, get a reference to the clicked element. I thought this code should work, and work across browsers: <script> function getit(e) { if (!e) var e = wind…
Top answer
1 of 2
3

about this values.

  1. Arrow functions capture and always use their lexical this value, meaning the one that was in effect when their arrow function expression was evaluated. Evaluation usually occurs when executing an assignment operation or when calculating parameter values for a function call which has arrow functions in its argument list.

    • Arrow functions cannot be used as constructors.
  2. Non arrow functions called as constructors using new (or super when extending a class) see the object under construction as their this value.

  3. Bound functions save and use a this value supplied as the first argument to the bind method of another function.

    • Bound functions ignore their saved this value if called as constructors - but this is rare enough to be considered an edge case and is not generally recommended.

    • Binding an arrow function has no effect on its this value but could be used to predefine a set of parameter values.

  4. Functions called using either their call or apply object methods take their this value from the (first) thisValue argument supplied to call or apply, subject to JavaScript mode:

    • In strict mode null or undefined values provided for thisValue are used as the function's this value. In sloppy mode however, null or undefined are replaced by window before making the call.

    • Arrow and bound functions can be called using these methods (e.g. to supply arguments) but use their own recorded this value.

  5. Provided none of the preceding rules apply, functions explicitly called as a method of an object use the object as their this value.

    E.G. in a call of form

    someObject.methodName( optionalArgumentList)
    

    this in methodName refers to someObject if the method is a regular function.

  6. In strict mode, the default value of this in an unqualified function call is undefined. In sloppy mode (dating from when JavaScript was first introduced) this is window. For demonstration:

function a () {
    "use strict";
    console.log("in strict mode functions the default this is ", this);
};
let b = function() {
    console.log("but in non strict mode,  the default this is ",
        this === window ? "window" : this
    );
}

a(); // undefined
b(); // window
  1. Code provided as a text string in calls to the global Function constructor, SetTimeout, related timer calls, and event attributes in HTML source, is treated as a "script" in its own right and creates a function that

    • operates in sloppy mode if strict mode is not invoked by the supplied source code,

    • operates in strict mode if strict mode is invoked in the source.

    While this alters the default this value of the function, is is also an edge case because none of these methods of creating a function is recommended when writing maintainable code.

  2. The this value when evaluating code with eval is outside the scope of this question, but for completeness:

    • Direct calls to eval inherit this from the calling context unless the evaluated code invokes strict mode - in which case this is undefined during code evaluation.

    • Indirect calls to eval use window (i.e. the global object) as this even if they invoke strict mode (Ref.)

    This is also an edge case since because of its dangers, eval should never be used because you can.


Inline event handlers in HTML

Event handler content attributes in an HTML tag of the form

    onEventName="text"

are converted into event handler functions by the HTML parser using steps equivalent to

  1. Save the text as the attribute's string value.

  2. Use the JavaScript parser/compiler to create an event handler function from the text by including it in a template of form

    function( event) {
          // include attribute text here as body code
    }
    
  3. Save the function as a property of the element under the same name as the attribute. E.G. at this point an element with an onclick text attribute will also have an onclick property which is a function.

  4. Add the function to the element's internal event handler map. In practical terms this means actual event handling uses a map of listeners rather than looking for handler functions on the element.

Warning

  • HTML onEventName attributes predate both standardization of the DOM and the introduction of addEventListener:

    Handlers created by the HTML parser have a legacy scope chain that minimally searches the element the event attribute belongs to, a surrounding form element if any, and the document object before reaching the global object when looking up names - which can result in obscure bugs.


question 1

Why with inline onlick, we have to write onclick="hello()", but in JS, we should write btn.onclick=hello or btn.addEventListener('click',hello);

The HTML event handler attribute is used as the body code of a event handler function created by the HTML parser. To call hello, attribute text must provide the source code to make the call, as in e.g. hello().

In JS, setting an onclick to a function object, or calling addEventListener with a function as the second parameter, adds the function to a map of handlers associated with the element. If parentheses are placed after the function name, using onclick as an example:

  onclick = myFunction();

the function is called and an attempt is made to use its return value as a handler function - and if the return value is not a function little happens. Most often this is a mistake and not the desired outcome.


question 2

For regular function, why with inline onclick, "this" refers to window, but with js call, "this" refers to button.

Inside the event handler function created from an inline onclick attribute, this does refer to the button. If you call out to another function with code like hello(), you are making an unqualified call to it, so the called function uses its default this value - i.e. window if the called function operates in sloppy mode.

Following on from "Inline event handlers in HTML", you could pass on this (referring to the button) and the event object as a parameter values if you wanted to:

onclick="hello(this, event)"

Handler functions provided in JavaScript go directly into the element's map of event handlers and are called by the event system with the button as their this value (probably using call or apply, since handlers added with addEventListener aren't maintained as element property values).


question 3

<button onclick="function tes(){console.log(this)}tes()">button>/button>

Creates the event handler function

function onclick(event) {
    function tes(){
        console.log(this)
    }
    tes()
}

Strict mode was not invoked in the button tag's event attribute text, so both onclick and tes are in sloppy mode. tes is called without qualification, so it uses and logs its default this value which is window.

In regards to "about this values", none of rules 1 - 5 apply, so rule 6 comes into effect.


question 4

<button onclick="console.log(this)">button</button>

creates a handler function

function onclick(event) {
    console.log(this)
}

which is called with the button element as its this value by the event system as it would for any other handler. console.log is showing the outer HTML for the button in the log. If you change this to a string, the log will tell you its an HTMLButtonElement element instead:

<button onclick="console.log(this.toString())">button</button>
2 of 2
1

The text hello() in the inline <button onclick="hello()"> is actually a small JavaScript program itself — you should never use this; it’s an obsolete old-fashioned way to make anything work and should be forgotten.

Instead, the correct way in JavaScript is like this:

function hello(){}

button.addEventListener("click", hello);

where hello is the name of a function (not a JavaScript program).

As for why this is the current button? All functions can be called with a different this.

You can call the hello function with a different this if you want to.

hello.call({ turkey: true });

That’s how you call hello and provide { turkey: true } as the this object.

It’s standard for HTML elements to call event handlers with the element as the this object.

🌐
GitHub
gist.github.com › c4d79d9f6784939ee6b8
how to pass this element to javascript onclick function · GitHub
how to pass this element to javascript onclick function · Raw · how to pass this element to javascript onclick function · This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.