Anuj TBE
Anuj TBE

Reputation: 9790

hide div which not contain class using jquery

I want to switch div on hover on li element.

My li element looks like

<ul>
  <li id="id1" onmouseover="subDivision(this.id)">first line</li>
  <li id="id2" onmouseover="subDivision(this.id)">second line</li>
  <li id="id3" onmouseover="subDivision(this.id)">third line</li>
</ul>

<div class="submenu id1">
   First division
</div>
<div class="submenu id2">
   Second division
</div>
<div class="submenu id3">
   third division
</div>

jQuery code :

<script>
  $('.submenu').hide();
  function subDivision(divId) {
    $('.'+divId).show();
    $('.submenu not(.'+divId+')').hide();
  }
</script>

I want to show div with class as passed id and hide all div under .submenu div which does not contain passed id.

But this is not hiding div and showing all division after another without hiding previous one.

Upvotes: 1

Views: 466

Answers (3)

Pranav C Balan
Pranav C Balan

Reputation: 115212

You are missing : in your pseudo-class selector although there is no need of space between them. If you added space it checks for descendants which don't have the class.

$('.submenu:not(.' + divId + ')').hide();
// --------^---------


The code can be even much more reducible

$('li[id^=id]') //  get all li element where id start with id
.mouseover(function() { // bind mouseover event handler instead of inline
  $('.submenu.' + this.id) // get the element to show
  .show() // show the element
  .siblings('.submenu') // get all its siblings
  .hide(); // hide them
})
.submenu {
  display: none
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul>
  <li id="id1">first line</li>
  <li id="id2">second line</li>
  <li id="id3">third line</li>
</ul>

<div class="submenu id1">
  First division
</div>
<div class="submenu id2">
  Second division
</div>
<div class="submenu id3">
  third division
</div>

Upvotes: 1

brk
brk

Reputation: 50291

You can use addClass & removeClass to show the div of concern on hovering li

function subDivision(divId) {
         $('.submenu').removeClass('showElem').addClass('hideElem');
          $('.'+divId).addClass('showElem');
    }

JSFIDDLE

Upvotes: 1

Rory McCrossan
Rory McCrossan

Reputation: 337560

Firstly you should use unobtrusive JS to attach your event handlers instead of the outdated on* event attributes. From there you can use a simple selector to toggle the relevant element by its class. Try this:

$('li').hover(function() {
  $('.' + this.id).toggle();
});
.submenu {
  display: none;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul>
  <li id="id1">first line</li>
  <li id="id2">second line</li>
  <li id="id3">third line</li>
</ul>

<div class="submenu id1">
  First division
</div>
<div class="submenu id2">
  Second division
</div>
<div class="submenu id3">
  third division
</div>

Upvotes: 3

Related Questions