In html I have a lot od DIVs with names(yes, names, not IDs) respectively p001, p002, p003... which are like this:
<div id="pole" name="p001"><img src=""></div>
<div id="pole" name="p002"><img src=""></div>
<div id="pole" name="p003"><img src=""></div>
etc...
In Javascript I have defined variable called 'pos' which contains a number, for now: "284" and a function which should change img src to "player.png". I tried 2 ways and none of these work:
document.getElementsByName('p'+pos).innerHTML='<img src="player.png">';
and
document.getElementsByName('p'+pos).getElementsByTagName("img").src="player.png";
How to change img src which is in specified DIV?
In html I have a lot od DIVs with names(yes, names, not IDs) respectively p001, p002, p003... which are like this:
<div id="pole" name="p001"><img src=""></div>
<div id="pole" name="p002"><img src=""></div>
<div id="pole" name="p003"><img src=""></div>
etc...
In Javascript I have defined variable called 'pos' which contains a number, for now: "284" and a function which should change img src to "player.png". I tried 2 ways and none of these work:
document.getElementsByName('p'+pos).innerHTML='<img src="player.png">';
and
document.getElementsByName('p'+pos).getElementsByTagName("img").src="player.png";
How to change img src which is in specified DIV?
Share Improve this question asked Jul 21, 2013 at 16:32 KyrtapKyrtap 1581 gold badge1 silver badge8 bronze badges 2- Your div's must have different ids if you want your html to be valid, and if you want to avoid javascript conflicts. – Stefan Commented Jul 21, 2013 at 16:36
-
1
div
elements don't define a"name"
attribute. Your code will fail in at least IE8 and lower when fetchingdiv
elements usinggetElementsByName
. – user2437417 Commented Jul 21, 2013 at 16:38
3 Answers
Reset to default 5getElementsByName
returns a list of elements, not a single element, so try:
document.getElementsByName('p'+pos)[0].
getElementsByTagName("img")[0].src="player.png";
You have to select the all "img" tags in html code. And then you can change the element's src in body or specified element.
images = document.querySelectorAll("#content_image img");
First of all, I think you should switch name
and id
attributes on your div
tags. You CANNOT have multiple elements with the same id but you can have multiple elements with the same name.
<div name="pole" id="p001"><img src=""></div>
<div name="pole" id="p002"><img src=""></div>
<div name="pole" id="p003"><img src=""></div>
To solve your problem you can use the firstChild
property of DOM if the img
will always be the first child of your div tag.
document.getElementById('p'+pos).firstChild.src="player.png";