I'm trying to run the same function on different divs with the same class. The thing is that I need the function to use offsetTop of each container and every div has a different value. The divs have the same class because I don't know how many divs are going to be present on each page of the site.
<!DOCTYPE html>
<html>
<body>
<div class="container-div">
<div class="element">Distance to top is </div>
</div>
<p>
.<br>.<br>.<br>.<br>
</p>
<div class="container-div">
<div class="element">Distance to top is </div>
</div>
<p>
.<br>.<br>.<br>.<br>
</p>
<div class="container-div">
<div class="element">Distance to top is </div>
</div>
<button onclick="myFunction()">Get distance</button>
<script>
function myFunction() {
var container = document.getElementsByClassName("container-div");
container[0].innerHTML = "Distance to top for this Div is" container.offsetTop;
container[1].innerHTML = "Distance to top for this Div is" container.offsetTop;
container[2].innerHTML = "Distance to top for this Div is" container.offsetTop;
}
</script>
</body>
</html>
From what I understand this is what you need, forEach loop trough all div's with class element. And you can get all div by class with document.querySelectorAll('.yourclass')
<!DOCTYPE html>
<html>
<body>
<div class="container-div">
<div class="element">Distance to top is </div>
</div>
<p>
.<br>.<br>.<br>.<br>
</p>
<div class="container-div">
<div class="element">Distance to top is </div>
</div>
<p>
.<br>.<br>.<br>.<br>
</p>
<div class="container-div">
<div class="element">Distance to top is </div>
</div>
<button onclick="myFunction()">Get distance</button>
<script>
function myFunction() {
// Get all divs
const divElements = document.querySelectorAll('.element')
// Loop trough all elements you selected
divElements.forEach(element => {
let distance = element.offsetTop;
element.innerHTML = 'Distance to top is: ' + distance;
});
}
</script>
</body>
</html>