开发者

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='someth开发者_JAVA百科ingelse'>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!


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';
}


You can use javascript function getElementsByTagName:

var listitems = document.getElementsByTagName("li");

this would return an array of all the lists and can be iterated for each list element and processed as required.


You can try:

In the case that you can have more than ul, first you have to get all references to them and then process each ul:

var uls = document.getElementsByTagName("ul");

    for (uli=0;uli<uls.length;uli++) {

        ul = uls[uli];

        if (ul.nodeName == "UL" && ul.className == "classname") {

            processUL(ul);

        }

    }

An illustration of proccessUL can be:

function processUL(ul) {

    if (!ul.childNodes || ul.childNodes.length == 0) return;

    // Iterate LIs

    for (var itemi=0;itemi<ul.childNodes.length;itemi++) {

        var item = ul.childNodes[itemi];

        if (item.nodeName == "LI") {

            // Iterate things in this LI
 in the case that you need it put your code here 
              .....
        }

    }

}

Of course you can also use: item.className = "classname"; if you dont need to iterate between childs of LI


document.getElementById('flash-menu').childNodes will also include white space nodes.

function updateMenu(view_name) {

    var list_items = document.getElementById('flash-menu').getElementsByTagName('li'), i; 

    for (i=0 ; i<list_items.length ; i++){
            if (list_items[i].className.indexOf('active') > -1) {
              list_items[i].className = list_items[i].className.replace(/\bactive\b/,'');
            }
        }
    document.getElementById(view_name).className += " active";
}


i agree with jensgram,and you'd better code like this:

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

add the regex string a 'g'


g is for Global ,using ‘/g’ can replace all the same Which Match the regex ,but if you don't use '/g',you just replace the first string . like this :

var test= "testeetest" ;
alert(test.replace(/e/,"")) ;//result : tsteetest but using 'g' var test= "testeetest" ;
alert(test.replace(/e/g,"")) ;//result : tsttst


Have a look at this here: https://developer.mozilla.org/en-US/docs/Web/API/element.classList It helped me a lot with finding class elements!


This is my solution, maybe not the best, but for my works fine.

window.addEventListener('load', iniciaEventos, false);
function iniciaEventos(e)
{
    var menu = document.querySelectorAll('nav li');
    for(var i = 0; i < menu.length; i++ )
        {
            menu[i].addEventListener('mousedown', clickMenu);
        }
}

function clickMenu()
{
    var menu = document.querySelectorAll('nav li');
    for(var i = 0; i < menu.length; i++)
            menu[i].classList.remove('active');

    this.classList.add('active');
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜