Question

This statement works. On the click of the node, i get a message displaying its ID.

 newnode.setAttribute("onClick", "alert(this.id)"); 

I need to pass the value of this.id to a different function and am struggling to get around it.

Attempt 1:

The below does not work; I understand that i cant pass this.id to another function, which does the same thing, because this is not relevant to anything within the test function:

newnode.setAttribute("onClick", "test(this.id)"); 

function test(f){
alert(f);
}

Attempt 2:

var testvar = newnode.id;
newnode.setAttribute("onClick", "test(testvar)"); 

function test(f){
alert(f);
}

Why is testvar not recognised in my setAttribute line?

Was it helpful?

Solution

newNode.onclick = function(){
  test(this.id);
};

function test(id){
  alert(id);
}

Example: http://jsfiddle.net/sHZeL/1/

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top