函数中的.getElementById()为空

时间:2018-01-21 14:12:43

标签: javascript html dom

也许这很愚蠢,但我无法理解在函数children中传输的输入参数有什么问题。

我正在尝试向函数children发送DOM中元素的ID - tableol,然后在console.log中输出这些元素。

<body>

<table id="table">
  <tr>
    <td>1</td>
    <td>2</td>
    <td>3</td>
  </tr>
</table>

<ol id="ol">
  <li>11</li>
  <li>22</li>
  <li>33</li>
  <li>44</li>
</ol>

<script>

    function children(elem) { 

        var idElements = document.getElementById('elem');
        console.log(idElements); // result - "null"

    }

    children(table); // get DOM element with id="table"
    children(ol); // get DOM element with id="ol"

</script>

</body>

2 个答案:

答案 0 :(得分:4)

function children(elem) { 
    var idElements = document.getElementById(elem);//remove ("") around elem variable

    console.log(idElements);

}
 //watch the quotations: send them AS STRINGS 
children("table"); // get DOM element with id="table"
children("ol"); // get DOM element with id="ol"

答案 1 :(得分:0)

您当前没有向children函数传递任何内容,因为table和ol都将是未定义的(您将它们作为未定义的变量传递),而是将它们作为字符串传递。此外,从不使用children函数的参数elem - 它应该传递给getElementById方法。

function children(elem) { 

    var idElements = document.getElementById(elem);
    console.log(idElements);

}

children('table'); // get DOM element with id="table"
children('ol'); // get DOM element with id="ol"