0

hi guys, I am doing some tests on e.currentTarget vs $(this) to get things clear in my head. It is said that the two are equivalent, so I created a test page with the following code in (among the other things of course):

<div class="testLink">
    <a href="#">Link</a>
</div>

The script goes:

    /*TESTS ON THE TESTLINK*/
    $(".testLink").click(function(e){
        e.preventDefault();
        console.log("e.currentTarget is " + e.currentTarget);
        console.log("this is " + $(this).html());
    });

    /*EN OF TESTS ON THE TESTLINK*/

And this is the result I get:

e.currentTarget is [object HTMLDivElement]
this is <a href="#">Link</a>

Now, first of all I would like to ask, how do I actually print the value of e.currentTarget to obtain an HTML tag as I did for $(this).html())?
Second - but perhaps more importantly - to me the results do not coincide: e.currentTarget seems to be returning the DIV containing the link and $(this) returns instead the expected result. Can anybody clarify please?
thanks

Edited by Violet_82

3
Contributors
3
Replies
32
Views
3 Years
Discussion Span
Last Post by Violet_82
0

e.currentTarget.html() should work
html() retuns the html inside of the <div> not the <div> itself

1

I'll answer your second question first since the solution will make more sense after that. What you're saying is correct, however it's your code implementation that's not corresponding to what you're TRYING TO SAY. You're trying to compare pure javascript to library implementations of javascript (in your case, jQuery) and that's not really going to work:

e.currentTarget === $(this) // false
e.currentTarget === this // true

e.currentTarget will typically be equal to this barring some sort of scope manipulation and NOT $(this). Javascript's this keyword returns the bare DOM element, but as soon as you put $() around it, what you've done now is converted it to a jQuery object.

Now for the solution. Because e.currentTarget returns a DOM object, you'll have to convert it to a jQuery function first using $() to be able to apply any jQuery methods on it, then access its HTML:

console.log("e.currentTarget is " + e.currentTarget);
// returns [object HTMLDivElement]

console.log("e.currentTarget is " + $(e.currentTarget).html());
// returns <a href="#">Link</a> which makes
// $(e.currentTarget).html() == $(this).html()

Edited by DJBirdi

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.