There are some misconceptions in your question:
The term "Parent" does not mean "relative"- Parent means "father".
Another thing is, in your code, there is no element father who owns a id
. The only element that is father of someone (same thing of grandfather) would be the <li>
, who is the father of div#oDeCima
who is the father of the link a#FilhoId
, so grandfather of a#FilhoId
:
<li> → pai de #PaiID e #oDeCima, e avô de #FilhoId
<a id="PaiId">Pai</a> → pai de ninguém, a não ser do nó de texto "Pai"
<div id="oDeCima"> → pai de #FilhoId
<a id="FilhoId" href="#" onclick="filhoPai(this)">Filho</a>
</div>
</li>
Why using the .eq()
is not working?
Because the method .eq()
returns an element at a certain position of a collection based on its index. Since any element can only have 1 direct parent; there is no collection of direct parents (there may be a collection of ancestors or parent collection: father, grandfather, great-grandfather etc.), then the .eq()
worthwhile 2
will return Undefined. As there can only be 1 direct parent, if you use .eq(0)
will work, but it is redundant to search for something by the index 0
if there is only him.
How could you find, as simply as possible, the desired id?
As there was a certain confusion as I mentioned above, I could not know exactly which id
you’re looking for.
If you are the parent of the clicked link you want to search for, you could use, in addition to the .parent()
, the method .closest("div")
. The difference between one and the other is that the .parent()
seeks the father of the element, whoever he may be. Already the .closest(seletor)
seeks the ancestor closest to the element that marries the selector (in his case, a div
):
function filhoPai(filho){
var filhoId = '#' + filho;
var pai = $(filhoId).closest("div").attr('id');
alert(filho + ' - ' + pai)
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<li>
<a id="PaiId">Pai</a>
<div id="oDeCima">
<a id="FilhoId"href="#" onclick="filhoPai(this.id)">Filho</a>
</div>
</li>
But in your case, really the .parent()
becomes simpler. The .closest(seletor)
is most useful when seeking an element in any position in ancestry.
If you want to take the id
of the element a#PaiId
, the best way is as proposed in the reply of Bruno Romualdo, because a#PaiId
is the parent of the clicked element and is before it (.pev()
). Now, the dial on .prev()
it would not be necessary, that is, instead of .prev("a")
, could just be .prev()
.
When I refer to "ancestor", I refer to the fiery hierarchy in the DOM: son, father, grandfather, great-grandfather, great-grandfather and so on.
I adjusted my answer, take a look if it helps.
– Bruno Romualdo