1

I am new to javascript programming. When i try to run this code, the default image in html tags shows up. I used the setAttribute function but it doesn't work. Please Help!

<!DOCTYPE HTML>
<html>
<head>
    <title>Javascript</title>
    <script type="text/javascript">

        var foo = document.getElementById("image");
        foo.setAttribute("src", "glasses.jpg");

    </script>
</head>

<body>
    <img src="awesomesite.gif" id="image" alt="Awesomesite">

    <p id="intro">
        Hello World
    </p>

</body>
</html>
ozil
  • 6,930
  • 9
  • 33
  • 56
Ayusch
  • 417
  • 7
  • 17

2 Answers2

1

either move the script to the bottom of your page or add the following to your script

document.onload(function()
{
    var foo = document.getElementById("image");
    foo.setAttribute("src", "glasses.jpg");
});
blairmeister
  • 915
  • 1
  • 6
  • 16
1
<!DOCTYPE html>

<head>
  <meta charset="utf-8">
   <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap.min.css">

  <style>
  </style>
</head>
<body>
    <img src="https://i.stack.imgur.com/xkF9Q.jpg" id="image" alt="Awesomesite">
    <p id="intro">
        Hello World
    </p>

  <script>

   window.onload = function () {

          var logo = document.getElementById('image');
          logo.src = "http://www.w3schools.com/html/pic_mountain.jpg";
    };


</script>    
</body>
</html>
Ritesh Karwa
  • 2,196
  • 1
  • 13
  • 17