Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting the parent from the matched element in jQuery

Tags:

jquery

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.

like image 353
jortsc Avatar asked Mar 24 '23 03:03

jortsc


2 Answers

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 match parents().eq() would probably be more appropriate.

like image 151
Dipesh Parmar Avatar answered Mar 26 '23 17:03

Dipesh Parmar


How about using:

 $(this).closest('.cli_visitas').css(...
like image 41
Lazarus Lazaridis Avatar answered Mar 26 '23 17:03

Lazarus Lazaridis