Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

document.getElementById(" ").src not working?

Tags:

javascript

I want to be able to choose the Battery 9 inside the dropdownlist.
I want the image of Battery 9 to show in the img tag.
Am I doing something wrong?

HEAD
function checkBatteryLife(){
if(document.getElementById('batterylifes').value == 'batterylife9'){
    document.getElementsByTagName('batteryID').src = 'battery9.png';
}
BODY
<img alt="" src="" name="batteryID" onclick="checkBatteryLife()">
</br>
<select id="batterylifes" onchange="checkBatteryLife()">
<option name="batteryIMG" value="batterylife9">Battery 9</option>
</select>
like image 912
FishBowlGuy Avatar asked Mar 10 '26 20:03

FishBowlGuy


2 Answers

The getElementsByTagName method will return a collection of tags by name, such as IMG or SELECT. Passing in the name attribute of a tag will not yield any results.

You should probably use getElementById and pass in the id of the element:

function checkBatteryLife() {
   if(document.getElementById('batterylifes').value == 'batterylife9')
   {
      document.getElementsById('batteryID').src = 'battery9.png';
   }
}

..

<img alt="" src="" id="batteryID" onclick="checkBatteryLife()" />
<br />
<select id="batterylifes" onchange="checkBatteryLife()">
   <option name="batteryIMG" value="batterylife9">Battery 9</option>
</select>

You can also use getElementsByName which will return a collection of DOM elements with the specified name property, and then iterate through it to find the correct one.

like image 107
Mike Christensen Avatar answered Mar 13 '26 16:03

Mike Christensen


You need .getElementsByName() function instead of .getElementByTagName():

document.getElementsByName('batteryID')[0].src = 'battery9.png';

As .getElementsByName() function returns list,and not a single element, for accessing list's element you need to use [] square brackets.Specifically you need first matched element with name="batteryID", that's why you should use[0].

like image 30
Engineer Avatar answered Mar 13 '26 15:03

Engineer



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!