andrewarnier
andrewarnier

Reputation: 177

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>

Upvotes: 0

Views: 121

Answers (3)

vanarajcs
vanarajcs

Reputation: 978

Use this at the bottom of your page.

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

Upvotes: 0

jfriend00
jfriend00

Reputation: 707318

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

Upvotes: 5

Amit
Amit

Reputation: 15387

Use as

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

ThegetElementsByClassName() 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

Upvotes: 0

Related Questions