简体   繁体   English

document.getElementsByClassName(“…”)[0]返回未定义

[英]document.getElementsByClassName(“…”)[0] returning undefined

I have a simple list and want to select the first element. 我有一个简单的列表,想选择第一个元素。

<ul>
  <li class="first">Test</li>
  <li>Test</li>
</ul>

My js: 我的js:

var list = document.getElementsByClassName("first")[0];
console.log(list);

But the console is saying undefined, why is that? 但是控制台说的是undefined,为什么呢? How should this be done the proper way? 应该如何正确地做到这一点?

Javascript Code is going to execute before the HTML code, so when the javascript interpreter executes a line var list = document.getElementsByClassName("first")[0]; JavaScript代码将在HTML代码之前执行,因此,当JavaScript解释程序执行一行时,var list = document.getElementsByClassName(“ first”)[0]; there was no list element is defined, because body element is not yet executed. 没有定义list元素,因为body元素尚未执行。

So to get it worked, put a javascript code inside a function and call that function using the "onload" event on body tag. 因此,要使其正常工作,请将javascript代码放入函数中,然后使用body标签上的“ onload”事件调用该函数。 By doing this, the function will get called after loading of complete <body> element. 这样,将在加载完整的<body>元素后调用该函数。

所以错误是在body标签之前输入了脚本标签,在我移到body末尾之后,它已修复

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM