Genome314
Genome314

Reputation: 505

Send src from img nested in div's

So what I want to do is send the src of an image that is nested in some div's to a javascript function when I click anywhere on the div info2. Here is my attempt, but it doesn't work. I know its something to do with traversing the DOM but I'm not learned enough to figure it out yet, any help would be appreciated! :)

div class="info2" onmousedown="returnDrop(this.div.img.src)" ondragover="allowDrop(event)" ondrop="drop(event)" >
<div  style="float:left">
<img class="myimg2"  style="max-height:80px;" src="Pictures/QuestionMark.png">
</div>
<div style="float:left;">
<p class="myname2">Name: Unspecified</p>
<p class="myprof2">Profession: Unspecified</p>
</div>
</div>

Upvotes: 0

Views: 45

Answers (1)

nnnnnn
nnnnnn

Reputation: 150040

Given that the img element is the only img descendant of the outer div you can do this without too much trouble:

onmousedown="returnDrop(this.querySelector('img').src)"

Demo: http://jsfiddle.net/fLjZA/

This makes use of the querySelector() method, which returns the first descendant element that matches the supplied CSS-style selector - in this case, 'img'. If there were multiple img elements to choose from within the outer div you could use a more specific selector that also included the class of the img you wanted, e.g., this.querySelector('img.myimg2').

Note: I don't really endorse embedding your JS code within html element event attributes, but I'm going to declare an explanation of alternative methods out of scope for this question...

Upvotes: 2

Related Questions