Reputation: 483
I have an array of 10 elements. At first I want to shuffle the array elements and display them (my current code does this). Then I want to show an alert
message if any of the displayed array elements are clicked. This is the thing I am having problem with. If, I am doing onclick
, it's showing me only 1 array element instead of all the 10 array elements and also showing the following error in console Uncaught TypeError: Cannot set property 'onclick' of undefined
. My code is (I am using only javascript
):
<script>
function shuffleArray(array) {
for (var i = array.length - 1; i > 0; i--) {
var j = Math.floor(Math.random() * (i + 1));
var temp = array[i];
array[i] = array[j];
array[j] = temp;
}
return array;
}
var myArray = ['1','2','3','4','5','6','7','8','9','10'];
newArray = shuffleArray(myArray);
for (i=0;i<newArray.length;i++) {
var p = document.write(newArray[i] + "<br >");
p.onclick = showAlert; // this is showing me only 1 array element and also showing error in concole
}
function showAlert() {
alert("onclick Event detected!")
}
</script>
Upvotes: 0
Views: 96
Reputation: 512
for (i=0;i<newArray.length;i++){
var p = document.write("<span class='no'>"+newArray[i] + "</span><br />");
}
function showAlert(){
alert("onclick Event detected!")
}
for(i=0;i<document.getElementsByClassName("no").length;i++){
document.getElementsByClassName("no")[i].onclick=showAlert;
}
Upvotes: 0
Reputation: 3170
Cannot set property 'onclick' of undefined
Here's your problem... p
is undefined.
Why?
Because document.write
does not return a DOM element. Actually it does not return anything at all (or, returns undefined
).
You want to:
document.createElement()
to create an element.p.innerHTML
to set the content (inner HTML) of your new element.Your code can be revised as suggested in @Johan's answer.
Upvotes: 0
Reputation: 35194
You need to create an actual element, rather than trying to bind events to strings:
for (i=0;i<newArray.length;i++) {
var p = document.createElement('p');
p.innerHTML = newArray[i];
p.onclick = showAlert;
document.body.appendChild(p);
}
Upvotes: 2