Building a website for a client but only for the mainpage I need to get a class on the main div for css purposes. For this I am trying to look for an active class on menu item for home, and if it has the active class, then add a different class to the main webpage's div.
so far i cant get much further then this:
<script>
$(document).ready(function() {
if $('li.level1.item101').hasClass('active');
$('#main').addClass('woodwork');}
});
</script>
the html involved for this (the li item) looks like this when active with the div somewhere down below in the page itself
<li class="level1 item101 active current"> </li>
<li class="level1 item102"> </li>
<div id="main"> </div>
my current code doesn't seem to be able to grab either the active li or the div, any help would be greatly appreciated
To check if the element contains a specific class name, we can use the contains method of the classList object.
To add a class to an element, without removing/affecting existing values, append a space and the new classname, like so: document. getElementById("MyElement").
First of all, you have some errors with your code, the html should be:
<li class="level1 item101 active current"> active</li>
<li class="level1 item102"> second</li>
<div id="main"> main </div>
and the javascript:
$(document).ready(function(){
if ( $('li.level1.item101').hasClass('active') ) {
$('#main').addClass('woodwork');
}
});
Here is a working fiddle
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With