Ethannn
Ethannn

Reputation: 191

Unable to get the id of an element

The JSFiddle below is a simplified example of what I am trying to accomplish. My code generates a. anchor element that is passed to a div. I'd like it to return its id when double clicked but get an undefined instead.

Can anyone tell me what I am doing wrong?

JSFiddle

function abc() {
    var myString = "<a onclick='bcd(this);' id='1'>krokodil</a>";
    document.getElementById("output").innerHTML = myString;
}

function bcd(e) {
        alert(this.id);
}

Upvotes: 1

Views: 81

Answers (4)

Tro
Tro

Reputation: 909

The problem is you are alerting the id of this, which is not equal to e in the scope of the function. Change the function to

function abc() {
    var myString = "<a onclick='bcd(this);' id='1'>krokodil</a>";
    document.getElementById("output").innerHTML = myString;
}

function bcd(e) {
        alert(e.id);
}
<button type="button" id="button" onclick="abc()">ADD</button>
<div id="output">kikker</div>

Upvotes: 1

user4961104
user4961104

Reputation:

change

alert(this.id); to alert(e)

Upvotes: 1

Callan Heard
Callan Heard

Reputation: 727

The parameter you are passing to the alert function is referenced as e, but you then attempt to alert this.id. this refers to the function calling the expression. Try this:

function abc() {
    var myString = "<a onclick='bcd(this.id);' id='1'>krokodil</a>";
    document.getElementById("output").innerHTML = myString;
}

function bcd(e) {
    alert(e);
}

Note that you also need to update the onclick() event to include the id property

Upvotes: 3

Quentin
Quentin

Reputation: 943097

The value of this depends on how you call the function.

Since you are calling bcd without an explicitly object (foo.bcd()) and are not in strict mode, the value will be equal to window (in a browser).

You are reading the id of the window, not the element.

Look at the e variable instead of this (since you pass it the element from the click event handler).

Upvotes: 3

Related Questions