Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 317
Jasper Doornbos Avatar asked May 13 '14 12:05

Jasper Doornbos


People also ask

How do you check an element has class or not?

To check if the element contains a specific class name, we can use the contains method of the classList object.

How do you add a class to an element?

To add a class to an element, without removing/affecting existing values, append a space and the new classname, like so: document. getElementById("MyElement").


1 Answers

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

like image 141
Razvan B. Avatar answered Oct 12 '22 02:10

Razvan B.