Sheida
Sheida

Reputation: 243

What is the context of "this" in this example?

Why do these two lines create different values for this?

<div>
  <a href="#" id= "li2" onclick="alert(this)"> a link </a> 
</div>
<p id= "p2" onclick="alert(this)"> a paragraph </p>

The first one alerts with the file's URI, the second one alerts with the "HTML Paragraph Element". So in other words, the second one context is the DOM element, but the first one is the main context.

I have done A LOT of research on this, and some of them are a bit over my head, so if someone knows the answer, can you dumb it down for me?

Upvotes: 22

Views: 896

Answers (3)

dfsq
dfsq

Reputation: 193261

The thing is that HTMLAnchorElement inherits methods from HTMLElement (naturally) as well as implements methods of URLUtils interface. The later in its turn has method toString which returns current href property.

When you alert anything it casts its arguemnt to string type, e.g. calling toString method of the argument. Hence the behavior you see.

HTMLParagraphElement (<p>) doesn't have this properties and hence toString of it simply returns default string [object HTMLParagraphElement].

Upvotes: 3

compid
compid

Reputation: 1323

For onclick events, the this variable is bound to the DOM element being clicked. When you call alert on variables in javascript, it actually calls toString(). When toString() is called on an anchor tag, the href attribute is actually returned. When called on the paragraph tag, it does not have a built-in toString() method and the default one is used (the one that simply prints [object objectName].

Upvotes: 3

gen_Eric
gen_Eric

Reputation: 227260

In inline JavaScript events, this is the element that the event was triggered on. These are both onclick events, so this is the element you clicked on.

When you use alert(), it converts its parameters to a string. When you convert an <a> element object to a string, you get its href value. When you convert a <p> element to a string, you just get [object HTMLParagraphElement] since it doesn't have a custom toString.

Revalent docs: https://developer.mozilla.org/en-US/docs/Web/API/URLUtils/toString

Upvotes: 28

Related Questions