-1

I'm trying to select an element by its class name instead of ID, as I have several elements with the same class name and I am trying to achieve the same effect on 'mouseenter' and 'mouseleave' for each of them.

This is the code I have so far:

var circle = document.getElementById('circle')
var timer

circle.addEventListener('mouseenter', function () {
  circle.classList.add('up')
  timer = setInterval(function () {
    circle.classList.toggle('up')
  }, 1000)
})

circle.addEventListener('mouseleave', function () {
  clearInterval(timer)
  circle.classList.remove('up')
})
body {
  width: 100%;
  height: 100vh;
  margin: 0;
  padding: 0;
  display: flex;
  justify-content: center;
  align-items: center;
}

div {
  width: 50px;
  height: 50px;
  background-color: blue;
  transition: transform 1s ease;
  border-radius: 50px;
}

div.up {
  transform: translateY(-20px);
}
<div id='circle'></div>

So, let's say for example, I want to have multiple boxes, and I want to set a single class "circle" for each of them, instead of creating a unique ID for each, "circle1", "circle2", etc and finding all those IDs, how do I just get the element by the class name and apply the same effect that I have right now?

David
  • 144
  • 1
  • 12

2 Answers2

1
var boxes = document.getElementsByClassName('box')

for (var i = 0; i < boxes.length; i++) {
    boxes[i].addEventListener('click', myFunction);
}

The above code selects the boxes with the class name box which returns a NodeList and we can iterate over the node list and add EventListener to each node.

Utkarsh
  • 50
  • 8
0

In Google a search javascript get element by class: tuto If u have one class to search

document.getElementsByClassName('test')

If u have 2

document.getElementsByClassName('rouge test')
YannickIngenierie
  • 602
  • 1
  • 13
  • 37