I've got a doubt:
Is this a good practice to find a parent which it's two levels above the matched element. The html structure looks like this:
<div class="cli_visitas left cli_bar hand" title="Control de las visitas del cliente">
<a href="/fidelizacion/visitas/nueva/id/<?php echo $cliente->getId();?>">
<span id="cli_visitas<?php echo $cliente->getId();?>" class="cli_bar_msg">La última visita <span class="lastvisit" ><?php echo $this->estados()->getUltimaVisita($cliente->getId());?></span></span>
</a>
</div>
'.lastvisit' fire the event, and I want to get the parent '.cli_visitas' div I'm doing this:
$(this).parent().parent().parent().css({boxShadow : '0px 0px 5px #DF0101',backgroundColor:'#F89494'});
Is this a good practice? I don't want to use .parents() method and iterate over each element and find the parent I'd like access it directly. I have tried with .get() but I think this method is not good for my propouse Is there another way to do it?
Thank you very much. Greetings.
You can do this using below two alternatives.
One
$(this).closest('div.cli_visitas')
Second
$(this).parents('div.cli_visitas')
$(this).parents('div.cli_visitas').eq(1)
Cool Explanation added in comment by Franc
As an additional note, for OP's benefit, on how those differ
.closest()
will get the first element that matches the selector traversing up through its ancestors in the DOM tree. It will stop as soon as it found a match.parents()
on the other hand will get all ancestors matching the specified selector, or all parent ancestors if no selector was specified. Therefore if you have a very large nested DOM tree,closest()
will be more efficient. Off course, if you need to access the nth-ancestor in the matchparents().eq()
would probably be more appropriate.
How about using:
$(this).closest('.cli_visitas').css(...
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With