Identifying the name of a class is simple enough.
event.target.className
However, determining if a specific element is the 3rd, 5th, or 11th one to use a particular class can be challenging, at least in my experience. I tried using the console (F12) to find a property that could help, but unfortunately, no luck.
In the following basic example, is there a way to identify whether the user clicked on ("box-a")[0]
, ("box-a")[1]
, ("box-a")[2]
, or ("box-a")[3]
? I understand that individual IDs can be used for each element, but I want to keep this as simple as possible if it's technically feasible.
let count;
for (count = 0; count < 4; count++) {
document.getElementsByClassName("box-a")[count].addEventListener("click", checker);
}
function checker() {
document.getElementsByClassName("box-b")[0].innerHTML = event.target.className;
}
// event.target.className points to the class name, but what identifies [0], [1], [2] or [3]?
.box-a {
background-color: green;
border: 0.6rem solid black;
padding: 10px;
font-family: arial;
font-size: 4rem;
}
.box-b {
display: block;
background-color: blue;
border: .25rem solid red;
padding: 10px;
font-family: arial;
font-size: 4rem;
}
<div class="box-a">Box 1</div>
<div class="box-a">Box 2</div>
<div class="box-a">Box 3</div>
<div class="box-a">Box 4</div>
<div class="box-b"></div>