简体   繁体   中英

Why getElementsByClassName does not work?

I'm trying to detect screen resolution then set position (like top,left) for multiple screen resolution,but it's not working. Anyone knows what's wrong with my code?

CSS:

.Scrolloutside
{
  position:relative;
  left: 550px;
 }

javascript:

  var nHeight = screen.height;
  var nWidth = screen.width; 
  if (nHeight ==714 && nWidth==1005)
 {
   //document.write("height:"+nHeight+" ,width="+nWidth+"<br>");
   var newsTarget = document.getElementsByClassName('Scrolloutside');
   newsTarget.style.top= "500px";
  }

html:

<div class = "Scrolloutside">
    <div class="scroller_title">News</div>
<div class="scroller_container">
    <div class="jscroller2_up">
    <?
    echo $secnews;
    ?>
    </div>
</div>
</div>
</div>

document.getElementsByClassName() returns a nodeList or HTMLCollection which are both a list of elements, not a single element. Even if there is only one matching element, it still returns a list with just one item in it. As such, you have to either get the first item in the list or iterate through the whole list (depending upon what your code wants).

Get the first item from the list (if you can assume there's only one item with the class name):

var newsTarget = document.getElementsByClassName('Scrolloutside');
newsTarget[0].style.top= "500px";

or iterate through the list (if there may be more than one item with that class name):

var newsTarget = document.getElementsByClassName('Scrolloutside');
for (var i = 0; i < newsTarget.length; i++) {
    newsTarget[i].style.top= "500px";
}

Use as

newsTarget[0].style.top= "500px";

The getElementsByClassName() method returns a collection of all elements in the document with the specified class name, as a NodeList object.

The NodeList object represents a collection of nodes. The nodes can be accessed by index numbers. The index starts at 0

在页面底部使用它。

newsTarget[0].style.top= "500px";

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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