addClass to an element at the top of the hierarchy

0

Here's a demonstration of what I'm trying to do ..

HTML

<div id="conteudo">   
<div id="inner" class="move">
        <div class="col-md-10"><a class="botao" href="#">botao</a></div>
        <div class="col-md-2">22222</div>
    </div>
</div>

JS

    $( ".botao" ).click(function( {
$( "#inner" ).addClass( "move-left" );
});
    );

CSS

#conteudo{overflow:hidden;width:100%;position;relative;height:200px;}     
#inner{height:200px;width:120%;}
    .move{left:0;position:relative;}
    .move-left{left:-20%;position:relative;background:#000!important}
    .col-md-10{width:80%;position:relative;float:left;}
    .col-md-2{width:20%;position:relative;float:left;}
    .botao{width:100px;height:100px;}

link

I want the contents of col-md-2 to come to the left when clicking on the button, and when clicked out of that element, remove the class move-left

    
asked by anonymous 14.02.2015 / 20:11

2 answers

4

More explicitly, you can use .closest() to modify any elements above in the hierarchy. The advantage over .parent() is that you do not have to chain multiple .parent() until you get to the desired element, because .closest() scans the entire hierarchical tree recursively until it reaches the element that meets the criteria. Based on your question, the example would be:

Picking up ID:

$( "a.botao" ).click(function() {
   $(this).closest('#inner').addClass( "move-left" );
});

Or by picking up the class:

$( "a.botao" ).click(function() {
   $(this).closest('.move').addClass( "move-left" );
});
    
15.02.2015 / 13:17
2

To access the above element in the hierarchy you can use the .parent() function:

$( "a.botao" ).click(function() {
   $( "#inner" ).parent().addClass( "move-left" );
});
#inner
.move{background:none;}
.move-left{background:#000}
.botao{width:100px;height:100px;}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script><divid="inner" class="move">
    <a class="botao" href="#">botao</a>
</div>
    
14.02.2015 / 20:16