Question

Im currently setting an LI here state through CSS like this:

body.className li.className {styles for here state}

However, I want to eliminated having to add new rules in the CSS file every time I add a new page. Instead, I would like to use JS to say [if the body.class is = to the LI.class, then add a class of "here" to the same LI.

Can someone assist with this logic?

No correct solution

OTHER TIPS

This should do if there is only one class name on the body element:

var bodyClass = $(body).attr("class");
$("li").is("."+bodyClass).addClass("here");

I am assuming you are trying this technique to set the 'active' class on a menu button for example 'here' as in 'you are here now' or 'the current page'?

this can of course be done by Javascript, but I doubt it's the best way.

javascript example: (with help of jQuery)

$(function() {
    var bodyId = $('body').attr('id');
    $('#menu li')            // find li tags in the menu list
        .removeClass('here') // remove previous occurance of 'here'
        .find('li.'+ bodyId) // find li with className equals to the body's 'id'
        .addClass('here');   // add the 'here' class to that Li tag.
});

remark 1 thing I did, was using the body's id to check if it is also present as a class on the LI, then I add the 'here' class. (I used the id because there could be more than 1 class on the body, then it is impossible to know which one.)

possible better way: you apparently already write the current page as a class on the body tag (may I assume this is done automatically via your server side code? php? asp? java?...) if you can write that, then you could add the logical test in your menu as well.

for example, where you loop over your menu items you could test if that specific menu item is the same as the current page being requested. then print a here class on the li. and then your css only needs li.here { /* current page styles */ }

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top