document.getElementByClassName Not working

Hi everyone
Attached is my code where I want background image of a div to be selected by js:

<!DOCTYPE html>

<html lang = "en">
<head>
  <title>to-forum.html</title>
  <meta charset="utf-8" />
  <style>
  .logo 
  {
    width:1200px;
    height:300px;
    margin:auto;
    display: block; 
    background-repeat:no-repeat;
    position:relative;
    border-radius: 25px;
  }
  </style>
    <script>
      function ChangeImage(param)
      { 
        switch(param)
        {
          case '1':
            return("images/greensilver.gif");
            break;
          case'2':				
            return("images/greensilver1.gif");
            break;
        }
      }
    </script>
</head>

<body>
  <div id="logo"> 
    <script>
      document.getElementByClassName("logo").style.backgroundImage = "url('" + ChangeImage('1') + "')";
    </script>
  </div>
</body>
</html>

No image shows up.
Could anyone correct my js code please (assuming there lays my problem)
Thanks

there is no document.getElementByClassName() because it’s document.getElementsByClassName() (note the s after Element) and that gives you a list, not a single element.

additionally, you don’t have a logo class either …

3 Likes

Move the script section at the end of Html body and change this line " document.getElementByClassName(“logo”) to document.getElementById(“logo”). This is working for me. Full content below

<!DOCTYPE html>
<html lang = "en">
<head>
  <title>to-forum.html</title>
  <meta charset="utf-8" />
  <style>
  .logo 
  {
    width:1200px;
    height:300px;
    margin:auto;
    display: block; 
    background-repeat:no-repeat;
    position:relative;
    border-radius: 25px;
  }
  </style>
 
</head>
<body>
  <div id="logo"></div>
 
</body>
   <script>
      function ChangeImage(param)
      { 
        switch(param)
        {
          case '1':
            return("images/greensilver1.gif");
            break;
          case'2':				
            return("images/greensilver1.gif");
            break;
        }
      }	
      
	 document.getElementById("logo").style.backgroundImage = "url('" + ChangeImage('1') + "')";
   
    </script>
</html>

Thank you scrumvisualize. The div “logo” should be attached to a class. I attached it to id by mistake ad I appologize for that.

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.