最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

html - Javascript - Change element's src in specified element - Stack Overflow

programmeradmin0浏览0评论

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 fetching div elements using getElementsByName. – user2437417 Commented Jul 21, 2013 at 16:38
Add a ment  | 

3 Answers 3

Reset to default 5

getElementsByName 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";
发布评论

评论列表(0)

  1. 暂无评论