What’s “this” in JavaScript onclick?

What’s “this” in JavaScript onclick?

here

What does this mean in the script?

Solutions/Answers:

Solution 1:

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

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

Solution 2:

It refers to the element in the DOM to which the onclick attribute belongs:

<script type="text/javascript"
        src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js">
</script>
<script type="text/javascript">
function func(e) {
  $(e).text('there');
}
</script>
<a onclick="func(this)">here</a>

(This example uses jQuery.)

Solution 3:

The value of event handler attributes such as onclick should just be JavaScript, without any “javascript:” prefix. The javascript: pseudo-protocol is used in a URL, for example:

<a href="javascript:func(this)">here</a>

You should use the onclick="func(this)" form in preference to this though. Also note that in my example above using the javascript: pseudo-protocol “this” will refer to the window object rather than the <a> element.

Solution 4:

In JavaScript this refers to the element containing the action. For example, if you have a function called hide():

function hide(element){
   element.style.display = 'none';
}

Calling hide with this will hide the element. It returns only the element clicked, even if it is similar to other elements in the DOM.

For example, you may have this clicking a number in the HTML below will only hide the bullet point clicked.

<ul>
  <li class="bullet" onclick="hide(this);">1</li>
  <li class="bullet" onclick="hide(this);">2</li>
  <li class="bullet" onclick="hide(this);">3</li>
  <li class="bullet" onclick="hide(this);">4</li>
</ul>

Solution 5:

Here (this) is a object which contains all features/properties of the dom element.
you can see by

console.log(this);

This will display all attributes properties of the dom element with hierarchy.
You can manipulate the dom element by this.

Also describe on the below link:-

http://www.quirksmode.org/js/this.html

Solution 6:

this referes to the object the onclick method belongs to. So inside func this would be the DOM node of the a element and this.innerText would be here.