addClass to an element above the hierarchy

Asked

Viewed 313 times

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;}

http://jsfiddle.net/35DJy/387/

I want that when I click on the boot the content of col-md-2 come left, and when clicked out of that element, remove the class move-left

2 answers

4


More explicitly, you can use the .closest() to modify any above element in the hierarchy. The advantage over the .parent() is that you don’t need to chain several .parent() to reach the desired element, because the .closest() scans the entire tree recursively recursively until you arrive at the element that meets the informed criteria. Based on your question, the example would be:

Picking up by the ID:

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

Or taking by the class:

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

2

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

$( "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>
<div id="inner" class="move">
    <a class="botao" href="#">botao</a>
</div>

  • Now how do I remove the class that was inserted if the user clicks on any screen area other than col-Md-2?

  • @That doesn’t have the class col-md-2 or that you are not restrained in a class element col-md-2?

  • I updated the question, see if it’s clearer...

  • @In this case I think you better ask a new question. This will basically change the whole answer.

Browser other questions tagged

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