how to change attribute in html using javascript

30,571

Solution 1

The most likely reason that your code is not working is that it is being executed before the element exists in the DOM. You should set your code up to run on the window load event or place it at the end of the document to ensure that the element exists before you try to access it.

<html>
<head>
   <title>Foo</title>
</head>
<body>

<img src="hi.jpg" width="100" height="100" id="cpul">
<script type="text/javascript">
   document.getElementById("cpul").src="hello.jpg";
</script>
</body>
</html>

Solution 2

Put in in the onload event for the window, so the code does not execute before the image html code has loaded. And use the width attribute to set width.

<html>
  <head>
    <title>Change my image width</title>
    <script type="text/javascript">
      window.onload = function() {
        var myImage = document.getElementById("cpul");
        myImage.src = "hello.jpg";

        // change width
        myImage.width = 200;
      };
    </script>
  </head>
  <body>
    <img src="hi.jpg" width="100" height="100" id="cpul"> 
  </body>
</html>
Share:
30,571
dramasea
Author by

dramasea

College Freshmen in Information system engineering

Updated on July 05, 2022

Comments

  • dramasea
    dramasea almost 2 years

    This is my code, so how can i change the width attribute?

    <html>
    <head>
    <script type="text/javascript">
     document.getElementById("cpul").src="hello.jpg";
    </script>
    </head>
    <body>
    
    <img src="hi.jpg" width="100" height="100" id="cpul">
    
    </body>
    </html>
    

    The above is fail and the image no change at all!!

    But why when i use this code(copy from other site), the image is change

    <html>
    <head>
    <title>JS DD Function</title>
    <script type="text/javascript">
        function jsDropDown(imgid,folder,newimg)
     { 
     document.getElementById(imgid).src="http://www.cookwithbetty.com/" + folder + "/" + newimg + ".gif";
     }
    </script>
    </head>
    <body>
    <table>
      <tr>
        <td>
    Foods: <select name="food" onChange="jsDropDown('cful','images',this.value)">
           <option value="steak_icon">Steak</option>
        <option value="salad_icon">Salad</option>
        <option value="bread_icon">Bread</option>
        </select><br />
         </td>
      <td>
             <img src="http://www.cookwithbetty.com/images/steak_icon.gif" id="cful">
    
    </body>
    </html>