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

Recommended Answers

All 3 Replies

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

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()

Ah, thanks DJBirdi, that's actually really clear, thanks!

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.