简体   繁体   中英

How to target image inside a div with an id with getelementbyid/tag/name?

Basically I want to change smiley.gif to landscape.jpg without changing divs and tags, but this code is not working. Any suggestions?

<div id="foo">
<div id="bar"><img src="smiley.gif">
Hello world!
</div>
</div>
<script>
getElementById("bar").getElementsByTagName("img").src="landscape.jpg";

</script>

getElementById is a method that you can only call on the document. getElementsByTagName will return a nodelist, and you need the first element in that nodelist:

document.getElementById("bar").getElementsByTagName("img")[0].src="landscape.jpg";
// Note the `[0]` here -----------------------------------^^^

JSFiddle

it will be better if you assign ID to img tag and use it like this

<div id="foo">
    <div id="bar"><img src="smiley.gif" id="myImg"> Hello world! </div>
</div>
<script>
    document.getElementById("myImg").src="landscape.jpg";
</script>

jsfiddle 1

or Use this

<div id="foo">
    <div id="bar"><img src="smiley.gif"> Hello world! </div>
</div>
<script>
   var obj = document.getElementById("foo");
   if(obj != null)
   {
      var images = obj.getElementsByTagName('img');
      images[0].src = 'landscape.jpg';
   }
</script>

As you have confirmed that the layout is fixed, then simply use.

document.getElementById('bar').firstElementChild.src = 'landscape.jpg';

This basically finds the unique element named bar , chooses the first child element (not firstChild , which could be an empty text node) and assigns the new value to src

Documentation on MDN

getElementById

firstElementChild

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM