Search id of relative element of relative

Asked

Viewed 254 times

5

Goal

Fetch the id the "father’s father" of an element.


Test scenario

function filhoPai(filho){

  var filhoId = '#' + filho;
  var pai = $(filhoId).parent().attr('id');
  
  alert(filho + ' - ' + pai)
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.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>

If I use .eq(2) to pull the Parent from the Parent, it does not work:

var pai = $(filhoId).parent().eq(2).attr('id');


Test reference

How do I get the n-th level Parent of an element in jQuery?


Doubts

  • Why using the .eq() is not working?
  • How could I seek, as simply as possible, the id desired?
  • I adjusted my answer, take a look if it helps.

3 answers

5


To catch a parent element of more than one level above use the .parents() jquery.

But a tag a cannot encompass another tag a, in your case need to take the Parent #oDeCima and use the function .prev() to get the previous one like this:

function filhoPai(filho){

  filho = $(filho);
  pai = filho.parent().prev("a").attr("id"); // pode usar o  id direntamente .prev("#PaiId") no luhar do a
  
  alert(filho.attr("id") + ' - ' + pai);
  
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<li>
  <a id="PaiId">Pai</a>
  
  <div id="oDeCima">
     <a id="FilhoId" href="#" onclick="filhoPai(this);">Filho</a>
  </div>
  
</li>

Notice you’re not the 'Father’s Father' like you’re thinking.

  • Bruno, in the example I’m using the .parents, but I want "father’s father"... that is, 2 levels above.

  • You want to get the id PaiId right?

  • Exactly. The way it is, it takes the "theCima".

  • Really, he’s not his father. I didn’t even notice. Thank you!

5

You did all the right research, but the code you’re using is parent and not the parents, another detail is that you want the father of the father that is to say id=1 because: father=0, father’s father=1, ...

//# Exemplo
var filho = $('#FilhoId'),
    pai_varA = filho.parent(),  // # resultado => <div id="oDeCima">
    pai_varB = filho.parents().eq(0),  // # resultado => <div id="oDeCima">
    paidopai = filho.parents().eq(1), // # resultado => <li>
    ahref = paidopai.find('a'); // # resultado => <a id="PaiId">Pai</a>

console.log('filho', filho.get(0));
console.log('pai_varA', pai_varA.get(0));
console.log('pai_varB', pai_varB.get(0));
console.log('paidopai', paidopai.get(0));
console.log('ahref', ahref.get(0));
    
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<li>
    <a id="PaiId">Pai</a>
    <div id="oDeCima">
        <a id="FilhoId" href="#">Filho</a>
    </div>
</li>

Tree Traversal, eq()

  • 1

    It worked too. + 1

2

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.

  • Sam, would be the "Paiid"... the "on top" of the id "the Devil"

Browser other questions tagged

You are not signed in. Login or sign up in order to post.