getelementbyclassname instead of getelementbyid is not working

无人久伴 提交于 2019-12-04 06:39:36

问题


I have read many times that you can NOW get getElementsByClassName. This below works fine IF I replace ClassName by Id, but using the word ClassName does not work. Anyone know why? (I tried on Chrome and Firefox)

      <script type="text/javascript">
        function makeDisable(){
        var x=document.getElementsByClassName("mySelect");
        x.disabled=true
        }
        function makeEnable(){
            var x=document.getElementsByClassName("mySelect");
             x.disabled=false
        }
     </script>

     <form>
        <select class="mySelect" id="mySelect">
        <option>Apple</option>
        <option>Banana</option>
        <option>Orange</option>
    </select>

        <input type="button" onclick="makeDisable()" value="Disable list">
        <input type="button" onclick="makeEnable()" value="Enable list">
    </form>

回答1:


The function is called getElementsByClassName. Plural. It returns not an element, but an array of all the elements that have the class name.

So even if the array consists of only one item, even there is only one element in the array, you still need to index it.

 x[0].disabled=true

instead of

 x.disabled=true

Fiddle



来源:https://stackoverflow.com/questions/17972331/getelementbyclassname-instead-of-getelementbyid-is-not-working

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!