user3387492
user3387492

Reputation:

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>

Upvotes: 0

Views: 6728

Answers (3)

PravinS
PravinS

Reputation: 2584

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>

jsfiddle1

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>

Upvotes: 0

Xotic750
Xotic750

Reputation: 23492

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

Upvotes: 0

George
George

Reputation: 36794

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

Upvotes: 2

Related Questions