I want to know which "child" element of a list was clicked without having to resort to the IDs, example: Suppose we have 2 lists(parent) and each of them has 3 links(children):
<ul class="padre">
<li><a href="#" class="hijo">Link1</a></li>
<li><a href="#" class="hijo">Link2</a></li>
<li><a href="#" class="hijo">Link3</a></li>
</ul>
<ul class="padre">
<li><a href="#" class="hijo">Link4</a></li>
<li><a href="#" class="hijo">Link5</a></li>
<li><a href="#" class="hijo">Link6</a></li>
</ul>
The only way to differentiate them without having to resort to "IDs" is with the position of an array:
var padre = document.getElementsByClassName('padre');
var array2D = new Array();
for (var i = 0; i < padre.length; i++) {
var posicionPadre = padre[i];
array2D[i] = posicionpadre;
var hijos = posicionPadre.children;
for (var j = 0; j < hijos.length; j++) {
var posicionHijo = hijos[j];
array2D[i][j] = posicionHijo;
}
}
And this way I capture when a click was made on the document:
document.addEventListener("click", function(evt){});
I would only need to know which child of its corresponding parent clicked. I propose this example without "ID" because if I keep adding links (children) to each of them I should put a different ID and it is a tedious job. You could also do auto-incrementing ID with javascript but it is not the case that I want to apply.
If you can, implement jQuery. It would look like this:
With this, there is no need to create arrays and no id. Depending on its type and class, you can get any attribute of the element when it is made
click
.It is not necessary to add ids to assign an event to an element. For example, we can select all
a
with classhijo
, which are direct children of ali
, which in turn is a direct child of aul
of classpadre
:And, by selecting them, we can assign an event to them.
Code:
I leave you an example
You must condition all the links with the click event, in your case there are 3:
and with the help of target you can identify which of the links was pressed, then with the name of the link you can work it so that you can access it, for example they would be called link_1, link_2, link_3 with the split you can cut and get 1, 2, 3
NOTE: the names son_1, son_2, son_3.......... you have to baptize them dynamically with a for