Re: Grab the 'this' keyword position



David wrote:
Is there a way to find which element in an object array the keyword 'this'
is acting upon?

For example:

function doMe(){
var aTags = document.getElementById("list").getElementsByTagName("a");
for (var i=0; i<aTags.length; i++) {
aTags[i].onclick=function() {
this.className = "myClass";
}
}
}

Inside of this function is there a way to determine where in the array this
'this' is and return the integer?

I'm not quite sure what you mean - if you want to remember the index
value 'i', then yes, you can do that, though you need to avoid a
closure otherwise the value of i will be the same regardless of which
'this' is called (it will be aTags.length).

Try:

aTags[i].onclick = (function(counter){
return function(event){
this.className = 'myClass';
alert(counter);
}
})(i);


The value of 'counter' inside the function is set to the value of 'i'
when the onclick handler is assigned.


var theID = this.somethingOrOtherThatWouldGiveMeTheNumber;
var elementID = document.getElementById("myDiv"+theID);

Replace your 'theID' with my 'counter' (or vice versa) and I think you
have it. :-)


--
Rob

.



Relevant Pages