I have the following code:
<script type="text/javascript" >
function showAlert()
{
alert("I am clicked"+this.innerHTML+this.index);
}
window.onload = function one()
{
var a1 = [1,2,3];
for (var i=0;i<a1.length;i++)
{
var p = document.createElement('p');
p.innerHTML = a1[i];
p.onclick = showAlert;
document.body.appendChild(p);
}
console.log("I am called");
}
</script>
this.innerHTML alerts the value of the element clicked but this.index shows undefined. How can I get the index value of array element clicked using javascript?
showAlertfunction,thisrepresents an html object which doesn't have anyindexattribute. you should store the array index value in theidattribute of the html element, or adata-XXXattribute.