无法访问HTMLCollection的值 [英] Can't access the value of HTMLCollection

查看:495
本文介绍了无法访问HTMLCollection的值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

test.html

test.html

<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
    <title>Untitled Document</title>
    <script>
    var eles = document.getElementsByClassName('review');
    console.log(eles);
    console.log(eles.length);
    console.log(eles[0]);
    // for(var i=0, max=eles.length)
    </script>
</head>
<body>
    <div class="review"></div>
    <div class="review"></div>
    <div class="review"></div>
    <div class="review"></div>
    <div class="review"></div>
</body>

我检查过eles代表HTMLCollenction。

I checked eles represents HTMLCollenction.

这里表示HTMLCollection还通过名称和索引直接将其成员公开为属性。

Here says HTMLCollection also exposes its members directly as properties by both name and index.

所以我尝试通过console.log(eles.length)和console.log(eles [0])进行调试。
但不幸的是,控制台显示0和未定义。(使用谷歌Chrome工具开发人员)

So I tried to debug by console.log(eles.length) and console.log(eles[0]). But unfortunately console shows 0 and undefined.(using Google Chrome Tool Developer)

如何访问eles的结果?
我想更改样式并为ClassName获取的标签添加属性。
另外,我只能使用自然的Javascript。

How can I access the result of eles? I want to change style and add attribute to the tags gotten by ClassName. Plus, I can only use natural Javascript.

推荐答案

问题是您已将脚本放在标题中在加载html元素之前执行,因此 getElementsByClassName()将不会返回任何元素。

The problem is you have placed the script in the header which gets executed before the html elements are loaded, so getElementsByClassName() will not return any elements.

一个解决方案是等待加载html元素然后执行你的脚本,为此你可以使用窗口对象加载事件

One solution is to wait for the html elements to be loaded then execute your script, for that you can use the window objects load event

window.addEventListener('load', function () {
    var eles = document.getElementsByClassName('review');
    console.log(eles);
    console.log(eles.length);
    console.log(eles[0]);
})

或您可以将脚本放在 body 元素的底部,而不是放在 head 中,以便在脚本运行时解析并执行元素加载在dom

Or you can place your script at the bottom of the body element instead of in head so that by the time the script is parsed and executed the elements are loaded in the dom

这篇关于无法访问HTMLCollection的值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆