Reputation:
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
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>
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
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
Upvotes: 0
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 -----------------------------------^^^
Upvotes: 2