Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pure javascript way to update CSS class attribute from all list items?

I'd like to use Javascript (not jquery) to access all items in a <ul> list and remove the active class from everything except my chosen menu item.

Here is the list:

<ul id='flash-menu'>
<li id="menu1" class='something active'>item 1</li>
<li id="menu2" class='somethingelse'>item 2</li>
<li id="menu3" class='somethingelse'>item 3</li>
</ul>

This is my javascript:

function updateMenu(view_name) {
var list_items = document.getElementById('flash-menu').childNodes; 
for (var i=0 ; i<list_items.length ; i++){
        list_items[i].className = list_items[i].className.replace('/\bactive\b/','');
    }
document.getElementById(view_name).className += " active";
}

The last line of the Javascript (adding the active class) works, but I don't think I'm accessing the list items right to remove the classes from the other items. Any suggestions? - thanks!

like image 758
AP257 Avatar asked Oct 13 '10 07:10

AP257


1 Answers

First off, your regex is wrong:

list_items[i].className.replace(/\bactive\b/, '');

Note: No quotes on regex'es in JavaScript. A slighty altered, working version is available on JsFiddle.


Furthermore, I get a few instances of HTMLTextElements in list_items. They're breaking the loop (Fx3.6/Win7) when trying to access the non-existing className attribute. You can avoid this by either using:

var list_items = document.getElementById('flash-menu').getElementsByTagName('li');
// Selecting _all_ descendant <li> elements

or by checking for the existence of .className before read/write within the loop body (example). The latter is probably the cleanest choice since it still only affects direct children (you may have several levels of <ul>s in each <li>).


I.e.,

function updateMenu(view_name) {
    var list_items = document.getElementById('flash-menu').childNodes; 
    for (var i=0, j=list_items.length; i<j; i++){
        var elm = list_items[i];
        if (elm.className) {
            elm.className = elm.className.replace(/\bactive\b/, '');
        }
    }
    document.getElementById(view_name).className += ' active';
}
like image 82
jensgram Avatar answered Jan 26 '23 16:01

jensgram