tags:

views:

38

answers:

2

I'm looking to dynamically highlight a tab, if it represents the current page. I have:

<style>
 #tabs li{bg-color: white;}
 body.Page1 #tabs .Page1,
 body.Page2 #tabs .Page2,
 body.Page3 #tabs .Page3{bg-color: orange;}
</style>
<body class="Page1 ADifferentClass">
 <ul id="tabs">
  <li class="Page1 SomeClass">
  <li class="Page2 SomeOtherClass">
  <li class="Page3 AnotherClass">
 </ul>
</body>

As you can see, there needs to be CSS for each tab, so adding another page involves modifying both the HTML and the CSS. Is there a simple (DRY) way to check if two divs have the same class already built into jQuery?

I ultimately went with this:

<script>
$(document).ready(function(){
  var classRE = /Page\d+/i;
  var pageType = $('body').attr('className').match(classRE);
  $('li.'+pageType).addClass('Highlight');
});
</script>
<style>
  #tabs li{bg-color: white;}
  #tabs li.Highlight{bg-color: orange;}
</style>
+2  A: 

How about having two common classes "Highlight" and "Normal".

<style> 
 #tabs li{bg-color: white;} 
 body.Page1 #tabs .Page1, 
 body.Page2 #tabs .Page2, 
 body.Page3 #tabs .Page3{bg-color: orange;} 
</style> 
<body class="Page1 ADifferentClass"> 
 <ul id="tabs"> 
  <li class="Highlight"> 
  <li class="Normal"> 
  <li class="Normal"> 
 </ul> 
</body> 
Aseem Gautam
Thanks for the response. This is likely part of the solution - It makes the CSS more DRY, but in order to apply the "Highlight" class dynamically, I still need to check if the <li> has the same class as the <body> in jQuery/Javascript - so I guess the core of the question is, "is the ability to check if two divs have the same class built into jQuery, or do I need to write the code myself?". Sorry for the lack of clarity up front.
T.R.
+1  A: 

You can check parents() length:

if ($('#myElement').parents('.myClass').length > 0)
mamoo
That's true, or, now that you mention it, $('#myElem').parents().hasClass('.myClass') It gets me most of the way there. Thanks
T.R.