Reputation: 483
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
?
Upvotes: 0
Views: 80
Reputation: 2297
I can suggest you a jQuery solution. You can use $(this).index() to get the element's index. Hope this helps.
Upvotes: -2
Reputation: 1073988
this.innerHTML alerts the value of the element clicked but this.index shows undefined.
That's because DOM elements don't have an index
property.
If you want to use the index (I assume you're talking about the i
value where you created the paragraph), you can store that on the DOM element in a data-*
attribute:
// In the loop creating the paragraphs...
p.setAttribute("data-index", i);
...and then use it via getAttribute
:
alert("I am clicked"+this.innerHTML+this.getAttribute("data-index"));
Technically, you could use an "expando" property as well:
// In the loop creating the paragraphs...
p.myReallyUniqueName = i;
...and then use it:
alert("I am clicked"+this.innerHTML+this.myReallyUniqueName);
...but doing so is generally not considered best practice, not least because you have to be careful not to use a name that may be used for something else in the DOM later. (I'd stay away from index
, for instance.) data-*
attributes are explicitly reserved for this kind of ad hoc information.
Upvotes: 3
Reputation: 11317
In your example this reference the paragrah element. So it doesn't have any property index.
One way to find the clicked index is to pass it as the paragraph's attribute like this :
function showAlert(){
alert("I am clicked"+this.innerHTML+this.getAttribute('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;
p.setAttribute("index", i); // Set the attribute index to <p>
document.body.appendChild(p);
}
console.log("I am called");
}
Upvotes: 0