开发者

What is wrong with this getElementsByClassName call in Javascript? [duplicate]

开发者 https://www.devze.com 2023-01-09 18:31 出处:网络
This question already has answers here: What do querySelectorAll and getElementsBy* methods retur开发者_运维知识库n?
This question already has answers here: What do querySelectorAll and getElementsBy* methods retur开发者_运维知识库n? (12 answers) Closed 8 years ago.

I am trying to access the width of a div to put in a cookie. This is the 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:

 document.getElementsByClassName(tab_panel).style.width

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


It's a string:

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

Bye

P.S. It's an array


document.getElementsByClassName("tab_panel") returns a collection of nodes, the first of which is referred to by 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.


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);
}


Try saying:

document.getElementsByClassName("tab_panel")
0

精彩评论

暂无评论...
验证码 换一张
取 消