0

Hello everyone: I'm having difficulty getting this code to work:

HTML:

        <div id='nav_bar'>
       <ul id="ul">
<li onmouseover="test();" > <a href='friends.php' class="first"  >Friends</a>                       </li>
          <li onmouseover="test();"> <a href='messages.php' class="first">Messages</a>              </li>
          <li onmouseover="test();"> <a href='index.php' class="first">Home</a>                     </li>
          <li onmouseover="test();"> <a href='profile.php?id=<?= $prof ?>' class="first">Profile</a></li>
          <li onmouseover="test();"> <a href='find_friends.php' class="first">Search</a>            </li>
          <li onmouseover="test();"> <a href='members.php' class="first">Members</a>                </li>
          <li onmouseover="test();"> <a href='logout.php' class="first">Log Out</a>                 </li>

       </ul>
    </div>  

JAVASCRIPT:

    function test(){
x = document.getElementsByClassName("first");
x.style.backgroundColor = "#ee7600";
x.style.border = "thin solid black";
}

The Javascript file is correctly referenced by the HTML file; I'm attempting to change the style of each element with class="first" in a nav bar. Why won't document.getElementsByClass() work?

Pat Green
  • 95
  • 1
  • 8
  • 1
    I really hope this is a contrived example and you're not actually using JavaScript to set styles on elements which have a particular class. – Anthony Grist Jul 28 '15 at 12:48

2 Answers2

3

getElementsByClassName returns an array-like live HTMLCollection.

style is a property of a single HTMLElement.

Loop over the HTML Collection and modify the style of each one in turn.

for (var i = 0; i < x.length; i++) {
    x[i].style.backgroundColor = "#ee7600";
    x[i].style.border = "thin solid black";
}
Quentin
  • 914,110
  • 126
  • 1,211
  • 1,335
1

getElementsByClassName returns a collection. For your example, try looping through and accessing each element in the loop getElementsByClassName("first")[index].

Honinbo Shusaku
  • 1,411
  • 2
  • 27
  • 45