How to iterate through ul list using Javascript?

后端 未结 4 1275
闹比i
闹比i 2020-12-28 18:54

I have the following HTML page (page is simplified here as it is a sample of the real one):





        
4条回答
  •  长发绾君心
    2020-12-28 19:55

    You should call getElementsByTagName() only once, caching the result.

    Then iterate over the collection like this (instead of using for/in).

    var a_elements = sender.parentNode.parentNode.getElementsByTagName("a");
    
    for (var i = 0, len = a_elements.length; i < len; i++ ) {
        a_elements[ i ].style.color = 'blue';
        a_elements[ i ].style.backgroundColor = '#FFFFFF';
    }
    sender.style.color = '#FFFFFF';
    sender.style.backgroundColor = '#000000';
    

    To get the target, you can pass it as the parameter in the inline onclick:

       
    

    Then your javascript can look like this:

    function Paint( sender ) {
    
        var a_elements = sender.parentNode.parentNode.getElementsByTagName("a");
    
        for (var i = 0, len = a_elements.length; i < len; i++ ) {
            a_elements[ i ].style.color = 'blue';
            a_elements[ i ].style.backgroundColor = '#FFFFFF';
        }
        sender.style.color = '#FFFFFF';
        sender.style.backgroundColor = '#000000';
    }
    

    Example: http://jsbin.com/aroda3/

提交回复
热议问题