Javascript function when clicking on any class="xpto"

0

I have a calendar where every day is:

<a class="dia" href="#">(Número do dia, ex: 1, 2, 3, etc)</a>

I did this below, but the problem is that I can only choose 1 class, I want it to work with either:

<a class="dia" href="#">1</a>
<a class="dia" href="#">2</a>

<script>
document.getElementsByClassName("dia")[0].onclick = function() {teste()};
function teste() {
    alert("Deu Certo!");
}
</script>
    
asked by anonymous 12.07.2017 / 19:49

3 answers

3

To select all elementos of a given class, you can use the querySelectorAll() function that returns a array with all elementos <a> that has the given condition, for example:

var dias = document.querySelectorAll('.dia'); 
// Seleciona tudo que tiver a classe dia
Now with the captured elements you need to add the click event to each, so you can use the forEach() function to go through each element within the dias variable and add eventListener click %:

function handleClick (event) {
    console.log('clicked');
}

dias.forEach(function(item){
    item.addEventListener('click', handleClick, {once: false});
});
    
12.07.2017 / 19:55
2

You can as Rafael suggested or add a global hearer, which serves as a delegate for elements not yet created when the page loaded. It would look like this:

document.body.addEventListener('click', function(e) {
    if (!e.target.classList.contains('minhaClasse')) return;
    // aqui podes correr o código ou chamar funções pois a classe foi clicada
});

document.body.addEventListener('click', function(e) {
  if (!e.target.classList.contains('minhaClasse')) return;
  // aqui podes correr o código ou chamar funções pois a classe foi clicada
  console.log('clicado!');
});
<button>Normal</button>
<button class="minhaClasse">Com classe</button>
    
12.07.2017 / 20:04
1

At this point, only the first link, [0] , is to be done. You can extend your logic to apply to all elements by using for :

var elementos = document.getElementsByClassName("dia");

for (var i = 0; i < elementos.length ; ++i){
  elementos[i].onclick = function() {teste()};
}

function teste() {
    alert("Deu Certo!");
}
<a class="dia" href="#">1</a>
<a class="dia" href="#">2</a>

Or using one of the new javascript syntaxes for of :

for (let elemento of document.getElementsByClassName("dia")){
  elemento.onclick = function() {teste()};
}

function teste() {
    alert("Deu Certo!");
}
<a class="dia" href="#">1</a>
<a class="dia" href="#">2</a>
    
12.07.2017 / 20:00