Search code examples
javascripthtmlcheckboxdrop-down-menuinternet-explorer-9

Create a drop down check box list in HTML with JavaScript


I need to create a drop down check box list like here. The problem with the code over there is that it is not working in IE9. I'm getting an error saying getElementsByClassName is not a property in the below code:

var checkList = document.getElementById('list1');
var items = document.getElementById('items');
        checkList.getElementsByClassName('anchor')[0].onclick = function (evt) {
            if (items.classList.contains('visible')){
                items.classList.remove('visible');
                items.style.display = "none";
            }

            else{
                items.classList.add('visible');
                items.style.display = "block";
            }


        }

        items.onblur = function(evt) {
            items.classList.remove('visible');
        }

Can someone please help me out on how to create a drop down check box list? Thanks.


Solution

  • The classList property is not available for an IE browser below 10. If you wanna do this you're gonna have to use className instead and check for the index of that class. For example:

    if (items.className.indexOf('visible') > -1){
                items.className -= 'visible';
                items.style.display = "none";
            }
    

    If your item has the visible class it will return its index and if it doesn't have that class it will return -1. I have created a fiddle from yours here to demonstrate