skunksts
skunksts

Reputation: 87

jquery cannot get elements id with 'this'

I'm kind of confused about 'this' in functions.

Why i dont get 'spanID' as id of the element on which i clicked?

HTML

<span id="spanID" onclick="alertIt()">something</span>

JS

function alertIt(){
    alert($(this).attr("id"))
}

here is JSfiddle

Upvotes: 0

Views: 86

Answers (7)

Jason P
Jason P

Reputation: 27012

Because when you create an inline event handler, you are creating an anonymous function:

onclick="alertIt()"

is like:

function() {
    alertIt();
}

An event handler bound using jQuery has the same behavior:

$('#spanID').click(function() {
    alertIt();
});

The anonymous function has the correct context, but the context won't be passed to other functions unless you do so explicitly:

onclick="alertIt(this)"

or

$('#spanID').click(function() {
    alertIt(this);
});

and

function alertIt(obj) {
    alert(obj);
}

onclick="alertIt.call(this)"

or

$('#spanID').click(function() {
    alertIt.call(this);
});

and

function alertIt() {
    alert(this);
}

Upvotes: 0

Jamen
Jamen

Reputation: 1

The this selector just get's the element it's nested in. Example:

$("#example").click(function(){
   $(this).fadeOut(500);
});

In your code, there was no element nesting the this selector .

Upvotes: 0

Kiran
Kiran

Reputation: 20313

You are facing an issue because $(this) within your function refers to the window object. You should pass this inside onclick="alertIt(this)" like:

<span id="spanID" onclick="alertIt(this)">something</span>
function alertIt(a){
    console.log(a.id);
}

DEMO

or

You should use jquery .click() event like:

<span id="spanID">something</span>
$("span").click(function(){
    alert($(this).attr("id"));
});

DEMO

Upvotes: 0

Pratik Joshi
Pratik Joshi

Reputation: 11693

Use following

$("span").on("click",function(){
    alert($(this).attr("id"));
})

working fiddle Fiddle

Upvotes: 0

Dave
Dave

Reputation: 4436

HTML

 <span id="spanID" onclick="alertIt($(this))">something</span>

Javascript

function alertIt(obj){
 alert($(obj).attr("id"))
}

jsfiddle

Upvotes: 0

Petroff
Petroff

Reputation: 828

add this to alertIt() function

<span id="spanID" onclick="alertIt(this)">something</span>

Upvotes: 1

Alvaro Hernandorena
Alvaro Hernandorena

Reputation: 610

I don't include the function call inside the span tag,

I just do:

<span id="spanID">something</span>

$(document).ready(function(){
    $("#spanID").click(function(){
        alert($(this).attr("id"));
    });
});

Upvotes: 1

Related Questions