Is there a way to check if a div has the same class as an ancestor in jQuery?
I want 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 must be CSS for each tab, so adding another page involves changing both HTML and CSS. Is there a simple (DRY) way to check if two divs have the same class already embedded in jQuery?
I ended up going 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 source to share
2 answers
How about having two generic classes "Select" 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>
+2
a source to share