Viraj Madushanka
Viraj Madushanka

Reputation: 71

Javascript add a class to element in a different div

$(document).ready(function() { 
   
    $('.btn').click(function() {
        $(this).parent().addClass('show');	
    });
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="container">
   <div class="row">
       <h4 id="txt1">Bookmark 1</h4>
       <a href="#" class="bokmarksave"> <img src="https://vignette.wikia.nocookie.net/secondlife/images/2/2b/Box.png/revision/latest?cb=20120226073326" class="hidden" width="100"></a>
      <p> Lorem Ipsum is simply dummy text of the printing and </p>
       <p class="page_num">Page 3 </p>
   </div>
   <div class="bookmark_icon"> 
      <a href="#"><img src="http://www.pngall.com/wp-content/uploads/2016/05/Click-Here-PNG-Images.png" width="100"class="btn"></a> 
   </div>
</div>

when we click the "click here" image with ".btn" class. I want to add a ".show" class to the image with ".hidden" class. I tied this with jquery but I can only add a class to the parent element.

Upvotes: 0

Views: 72

Answers (4)

Maz
Maz

Reputation: 113

In this specific case, you can just target the element with the hidden class by using the related jQuery selector.

$(document).ready(function() { 
    $('.btn').click(function() {
       $('.hidden').toggleClass('show');
    });
});

Upvotes: 0

Jeto
Jeto

Reputation: 14927

Try this:

$(this).closest('.container').find('.hidden').addClass('show');

However, a better practice would be to add some data- attributes to the appropriate elements in your HTML, and navigate using them. This could mean something like this:

$(this).closest('[data-container]').find('[data-bookmark-image').addClass('show');

edit: as @sheriffderek mentioned, removing the hidden class would probably make sense as well/instead.

Upvotes: 1

raah
raah

Reputation: 71

The parent element for the img is the a tag. Move the btn class to the a element and it will still works.

Upvotes: 0

Istiaque Ahmed
Istiaque Ahmed

Reputation: 6498

Just use the following JS:

$('.btn').click(function() {

  $(".hidden").addClass('show');

});

The image with class 'hidden' is selected as $(".hidden");

Upvotes: 0

Related Questions