Javascript 中的 getElementsByClassName 调用有什么问题?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3391791/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-25 01:03:03  来源:igfitidea点击:

What is wrong with this getElementsByClassName call in Javascript?

javascript

提问by David Willis

I am trying to access the width of a div to put in a cookie. This is the div:

我正在尝试访问要放入 cookie 的 div 的宽度。这是div:

 <div class="tab_panel" style="width:600px">

It is the only div with this class name. It is not an option to specify a unique id for the div. This is the code I have been using in an event to call it but it gives an error:

它是唯一具有此类名称的 div。为 div 指定唯一 id 不是一个选项。这是我在一个事件中使用的代码来调用它,但它给出了一个错误:

 document.getElementsByClassName(tab_panel).style.width

I know Firefox supports getElementsByClassName, so what am I doing wrong?

我知道 Firefox 支持getElementsByClassName,所以我做错了什么?

回答by Enrico Murru

It's a string:

这是一个字符串:

document.getElementsByClassName("tab_panel")[0].style.width

Bye

再见

P.S. It's an array

PS 这是一个数组

回答by kennebec

document.getElementsByClassName("tab_panel")returns a collection of nodes, the first of which is referred to by document.getElementsByClassName("tab_panel")[0].

document.getElementsByClassName("tab_panel")返回节点集合,其中第一个由 引用document.getElementsByClassName("tab_panel")[0]

If the node you are searching does not have an inline style="width:' assignment, an empty string is returned from document.getElementsByClassName("tab_panel")[0].style.width.

如果您搜索的节点没有内联 style="width:' 赋值,则从 返回一个空字符串document.getElementsByClassName("tab_panel")[0].style.width

回答by Sarfraz

Missing quotes:

缺少报价

document.getElementsByClassName('tab_panel').....

You should iterate over all elements like this:

您应该像这样迭代所有元素:

var elms = document.getElementsByClassName('tab_panel');

for(var i = 0 ; i < elms.length; i++)
{
   alert(elms[i].style.width);
}

回答by Justin Ethier

Try saying:

试着说:

document.getElementsByClassName("tab_panel")