0

It's easy to change class 'day' with addEventListener if I specify it with day[2], day[3] etc.

I don't really want to write all that code for each of them, how could I catch the class' order number "day[?]" when it's clicked, so I could use it in changeDate().

Parts of current code:

var day = document.getElementsByClassName("day");

day[2].addEventListener("click", changeDate);

function changeDate() {
  console.log("hit");
}
<li class="day">1</li>
<li class="day">2</li>
<li class="day">3</li>
George
  • 6,630
  • 2
  • 29
  • 36
Levi
  • 141
  • 1
  • 9

4 Answers4

2

In the changeData() function, you are able to access to this. It's the associated <li> (which were clicked), so use this.innerHTML to get the number of the day.

BNilsou
  • 886
  • 8
  • 22
0

Get all of the classes and loop through them to add listeners, like this:

var days = document.getElementsByClassName('day');
for(var i = 0; i < days.length; i++){
    days[i].addEventListener('click', changeDate);
}

EDIT: sorry, missed the last line: Your change date function can then include the following:

function changeDate(){
     var day = this.textContent;
};

Now the day variable in the text inside the element that was clicked.

Donnie D'Amato
  • 3,832
  • 1
  • 15
  • 40
  • This doesn't address the question: *how could I catch the class' order number "day[?]" when it's clicked, so I could use it in changeDate()* – Quentin Feb 21 '17 at 12:05
0

You can use the following code using standard javascript to find and attach click event handlers to all .day HTML elements.

<body>
<li class="day">1</li>
<li class="day">2</li>
<li class="day">3</li>
...
</body>

<script>
var dayArray = [];

window.onload = function(){

  dayArray = document.getElementsByClassName("day");
  
  for (var i = 0; i < dayArray.length; i++) {
    dayArray[i].addEventListener('click', changeDate, false);
  }

};

function changeDate(evt){
   console.log(this); // Here 'this' refers to the clicked HTML element
}
</script>

Hope this helps.

Levi
  • 141
  • 1
  • 9
BFG
  • 783
  • 8
  • 19
-2

Addition to @fauxserious answer you could try this:

var days = document.getElementsByClassName('day');
for(var i = 0; i < days.length; i++){
    days[i].addEventListener('click', changeDate);
}

function changeDate(){
   console.log('Clicked day ' + this.innerHTML);
}
lenny
  • 2,978
  • 4
  • 23
  • 39
  • No. That will call `changeDate` **immediately** and assign its return value as the event listener (since that return value is `undefined` with your code, it won't attach an event listener at all). – Quentin Feb 21 '17 at 12:11