getElementByID works, getElementsByClassName does not [duplicate]

倾然丶 夕夏残阳落幕 提交于 2019-12-02 08:59:37

问题


I'm working on a solution that dynamically adds select input / dropdown boxes to a page. The example code below works if I give each select input a unique id and include a line of cod4e to the script using getElementById() but does not work if I use GetElementsByClassName().

My objective is to use one script to populate select input box without the need to assign a unique id to select inputs and corresponding code to the script.

    <select class="p1"></select>
    <select class="p1"></select>
    <select class="p1"></select>

    <script>
    var Date1 = "<option>" + new Date(new Date().getTime()+(1*24*60*60*1000)).toDateString() + "</option>";
    var Date2 = "<option>" + new Date(new Date().getTime()+(2*24*60*60*1000)).toDateString() + "</option>";
    var Date3 = "<option>" + new Date(new Date().getTime()+(3*24*60*60*1000)).toDateString() + "</option>";
    var Date4 = "<option>" + new Date(new Date().getTime()+(4*24*60*60*1000)).toDateString() + "</option>";
    var Date5 = "<option>" + new Date(new Date().getTime()+(5*24*60*60*1000)).toDateString() + "</option>";
    var Date = Date1 + Date2 + Date3 + Date4 + Date5

    document.getElementsByClassName("p1").innerHTML = Date;
    </script>

回答1:


The getElementsByClassName() function (note the s in "Elements") returns a NodeList, not a single node. You have to iterate through the list to operate on each node individually.

You can do it with a simple for loop:

var selects = document.getElementsByClassName("p1");
for (var i = 0; i < selects.length; ++i)
  selects[i].innerHTML = Date;

I suspect strongly that your code has another problem: you're creating a global variable called "Date", and that will clobber the JavaScript "Date" constructor binding. Use another name (like lower-case "date").



来源:https://stackoverflow.com/questions/29593365/getelementbyid-works-getelementsbyclassname-does-not

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