javascriptadaptive-design

Javascript / Get an image element on page and but it in div (getElementByID)


For a banner, I need to put an image who are displayed on the same page. I'm really bad as developpement - So, I use this way - But, indeed, it doesn't work...

<!doctype html>
<html lang="fr">
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no">
  <meta name="ad.size" content="width=300,height=600">
  <title>Stack</title>
  <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script> 
  <link href='https://fonts.googleapis.com/css?family=Open+Sans:400,700' rel='stylesheet' type='text/css'>
</head>
<body>
  <a id="clickThroughBtn" href="javascript:window.open(window.clickTag)">
  <div id="border">
    <div id="container">
      <div class="border2">
        <div id="logo_bg"></div>
        <div id="red_c" class="logo_element"></div>
        <div id="rays" class="logo_element"></div>
        <div class="logo"><img src="logo_fr.svg" alt="Cofidis" /></div>
        <div class="title">
          Test
          <div id="adaptive">
            <script>
              function getImgs(){
                var Adaptive = document.getElementsByID('thumb0').img;
                Adaptive[0].style.width="200px"; // Taille de l'image
                Adaptive[0].style.width="200px"; // Hauteur
              }
            </script>
          </div>
        </div>
      </div>
    </div>
    </a>
    <img id="thumb0" src="http://gmz2.zarbi.be/avatars/m/1/1116.jpg?1404045273.jpg" />
</html>

The most important part -

<!-- Adaptive -->
<div id="adaptive">
  <script>
    function getImgs(){
      var Adaptive = document.getElementsByID('thumb0').img;
      Adaptive[0].style.width="200px"; // Taille de l'image
      Adaptive[0].style.width="200px"; // Hauteur
    }
  </script>
</div>
<!-- Adaptive -->

Thank you everyone ! Ludovic


Solution

  • You need to change this:

    var Adaptive = document.getElementsByID('thumb0').img;
    Adaptive[0].style.width="200px";                       // Taille de l'image
    Adaptive[0].style.width="200px";                       // Hauteur
    

    To this:

    var Adaptive = document.getElementById('thumb0');
    Adaptive.style.width="200px";                         // set image width
    Adaptive.style.height="200px";                        // set image height
    

    as there is no such method getElementsByID in the document object.

    Also, getElementById returns a single element. If you need to get multiple objects, then getElementsByName, getElementsByClassName and getElementsByTagName will work for you.