Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why "this" argument in jQuery returns href with anchors

I have this for exemple:

<div id="example">
    <a href="http://www.google.com/#1">Hello</a>
    <a href="http://www.google.com/#4">Hello</a>
</div>

And this two line of jQuery:

jQuery("a").filter(function() {
    console.log(""+this+"")
});

Returns:

 http://www.google.com/#1

 http://www.google.com/#4

But

jQuery("a").filter(function() {
    console.log(this);
});

Returns

<a href="http://www.google.com/#1">Hello</a>​

<a href="http://www.google.com/#4">Hello</a>​

Why the line 2, return the HREF attribute of the anchor IF 'this' argument add a "string"? The jQuery docs says if filter have an function argument, the "this" is the current DOM element

like image 326
jaikme Avatar asked Feb 20 '13 16:02

jaikme


1 Answers

""+this is equivalent to this.toString(). On an a element it returns the href (yes, that's weird, and probably for compatibility with something that was useful a long time ago, but that's what it does on all browsers).

In the second case, you're not calling toString but the browser dependent console formatting method. Different choices were made : on Chrome for example it usually returns the outer html (as a browsable tree if it's big).

like image 92
Denys Séguret Avatar answered Oct 23 '22 09:10

Denys Séguret