简体   繁体   中英

Check if element has the class active, if so, add class to a different element

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

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 this is your HTML

<ul>
    <li class="level1 item101 active current"> </li>
    <li class="level1 item102"> </li>
</ul>
<div id="main"> </div>

The JavaScript should look like this

$(document).ready(function(){
    if ($('li.item101').hasClass('active'))
        $('#main').addClass('woodwork');
});

Here I just look if the Listelement with the class item101 has the class active, if it is so I give the div-Tag with the ID main the class woodwork

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM