fegiar
fegiar

Reputation: 29

jQuery find() not working with prev()

I'm probably doing it the wrong way so that is why I need your help. I have set up a jsfiddle here: https://jsfiddle.net/m35o8jjL/2/

HTML:

$( ".layered_subtitle_heading" ).click(function() {
  $(this).prev().find('.layered_close').toggleClass('closed');
  $(this).prev().find('.layered_filter_ul').toggle();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<div class="layered_filter">
  <div class="layered_subtitle_heading clearfix">
    <span class="layered_subtitle">Metall</span> 
    <span class="layered_close"> <a href="javascript:;" data-rel="ul_layered_id_feature_9"></a> </span>
  </div>
  <ul id="ul_layered_id_feature_9" class="layered_filter_ul ">
    <li class="nomargin hiddable filter_lg">
      <div class="checker" id="uniform-layered_id_feature_38">
        <span>
          <input type="checkbox">
        </span>
      </div>
      <label for="layered_id_feature_38">
        <a href="#">925  Sterling Silber</a> 
      </label>
    </li>
  </ul>
</div>

Basically , what I want is when user clicks on the layered_subtitle_heading div, class toggles of the layered_close span , same with the display of the ul.

I'm probably not using prev() correctly but I really can't think of any way to make this work.

I have multiple layered_filters and that is why I have to use $(this).

Upvotes: 0

Views: 82

Answers (3)

Aiyaz Khorajia
Aiyaz Khorajia

Reputation: 598

Try this

  $(document).ready(function(){
      $( ".layered_subtitle_heading" ).click(function() {
          $(this).parent().toggleClass('closed');
      });
  });

Upvotes: 0

DesignMonkeyJim
DesignMonkeyJim

Reputation: 1935

to fix it remove .prev() and add .siblings() to get the ul to toggle

 $( ".layered_subtitle_heading" ).click(function() {
     $(this).find('.layered_close').toggleClass('closed');
     $(this).siblings('.layered_filter_ul').toggle();
     // you need to use alert()
     alert('da');
 });

and you hadn't added jQuery to your fiddle - https://jsfiddle.net/Jim_Miraidev/m35o8jjL/13/

Upvotes: 1

Pointy
Pointy

Reputation: 413737

The .prev() method is for navigating to the previous sibling. Your target <div> does not have a previous sibling; it's the first child of its parent.

What you probably want to do instead is

$(this).parent().find('.layered_close').toggleClass('closed');

or, to be a little more resilient to change:

$(this).closest(".layered_filter").find('.layered_close').toggleClass('closed');

Upvotes: 1

Related Questions