-1

I want to create a function which manipulates an element with a specific class. So far I have this:

function myFunc() {
var ball = document.getElementsByClassName('ball');
var myBall = 0;

myBall = ball[0].innerHTML; // HERE I NEED TO GET THE CURRENT BALL CLICKED

myBall[0].innerHTML = ++nr; // THE SAME HERE

}

The problem is that I don't know how to get the exactly div with the class:ball which was clicked. I know that myBall[0] is wrong. I need to set somehow the number representing the element clicked.

My HTML:

<div id="container">
    <div class="ball" onclick="myFunc()">1</div>
    <div class="ball" onclick="myFunc()">1</div>
    <div class="ball" onclick="myFunc()">1</div>
</div>
Florin Pop
  • 5,105
  • 3
  • 25
  • 58

1 Answers1

4

Something like this

var elems = document.querySelectorAll('#container .ball');
    
for (var i=elems.length; i--;) {
    elems[i].addEventListener('click', myFunc, false);
}
    
function myFunc() {
  
    this.innerHTML = parseInt(this.innerHTML, 10) + 1;
    
}
<div id="container">
    <div class="ball">1</div>
    <div class="ball">2</div>
    <div class="ball">3</div>
</div>
    
adeneo
  • 312,895
  • 29
  • 395
  • 388
  • Why I have to add for each an event listener? How it knows now what element I am clicking? – Florin Pop Feb 24 '15 at 18:32
  • Because that's the proper way to do it, unless you have a deLorean and can go back to 1997, when inline event handlers was fine. – adeneo Feb 24 '15 at 18:33
  • Came here to post this. Nice job. Here's my fiddle of almost the same thing: http://jsfiddle.net/jasonwilczak/tx2aqg4x/1/ – JasonWilczak Feb 24 '15 at 18:37
  • What if I want to add more "balls" while the script is running? Maybe have a button which adds another ball. – Florin Pop Feb 24 '15 at 18:39
  • 1
    @FlorinPop I believe that is a pretty well known question that you could find in this site. Here is a 'best practice' type post: http://stackoverflow.com/questions/2946656/advantages-of-createelement-over-innerhtml – JasonWilczak Feb 24 '15 at 18:41