Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to change attribute in html using javascript

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>
like image 1000
dramasea Avatar asked Sep 01 '26 15:09

dramasea


1 Answers

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>
like image 94
tvanfosson Avatar answered Sep 03 '26 04:09

tvanfosson