Shikhar Srivastava
Shikhar Srivastava

Reputation: 149

how to access a image tag from the external div with some id?

i have a code in which there is a image tag which is inside the div's tag with some id i want to access the image tag property src & then change it but i want this generalized javascript code.

my code is:

<div id="p5pg5QXlX-an-obj-16">
<div><img height="89" width="89" src="assets/rplay.png"></div>
</div>

& my javascript code is:

playButton=document.getElementById("p5pg5QXlX-an-obj-16");

now how i can access the src property of image tag by variable playButton?

Upvotes: 0

Views: 64

Answers (3)

carraua
carraua

Reputation: 1528

You can use the querySelectorAll function and use a CSS selector.

var playButton = document.querySelectorAll("#p5pg5QXlX-an-obj-16 img")[0];

You can change src like this later:

playButton.src = "someothersrc"

Upvotes: 2

Muhammet
Muhammet

Reputation: 3308

Update: if you want to change the src, just set your new image url:

var playButton=document.getElementById("p5pg5QXlX-an-obj-16");

playButton.getElementsByTagName('img')[0].src = "http://i.imgur.com/RLKixQW.png"; // here
<div id="p5pg5QXlX-an-obj-16">
<div><img height="89" width="89" src="assets/rplay.png"></div>
</div>

Upvotes: 2

stephenspann
stephenspann

Reputation: 1843

Using getAttribute(): http://www.w3schools.com/jsref/met_element_getattribute.asp

Note, you have to remove all spaces between elements in the HTML.

var playButton=document.getElementById("p5pg5QXlX-an-obj-16").childNodes[0].childNodes[0].getAttribute("src");

Working Fiddle:

https://jsfiddle.net/spanndemic/ghn2oner/

Upvotes: 1

Related Questions