简体   繁体   中英

Traverse the DOM to passback an image

Ok so I want to click on the image '.escape' and passback the source of the image '.myimg2' onclick. Below is my attempt at doing this: I know it is just traversing the DOM but I don't know how to traverse the DOM very well. Thanks for any enlightenment.

<table class="table2">
    <tr>
        <td>
            <div class="info2" ondragstart="return false" 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>
                <img class="escape" onclick="returnDrop(this.parentNode.childNode[0].src)" style="max-height:8px;" src="Pictures/escape.png">
            </div>
        </td>
</tr>
</table>
this.parentNode.getElementsByClassName('myimg2')[0]

演示: http//jsfiddle.net/ENQFX/

You're talking about IDs ( #escape ) but you're using classes ( .escape ). You should switch your class attributes to IDs because they're unique. Here I'll use the class though. You should put this in your onclick= attribute inside .escape .

this.setAttribute('src',this.parentNode.getElementsByClassName('myimg2')[0].getAttribute('src'))

Here we set the the src attribute to be that of the first .myimg2 class element that is inside .escape 's parent element. If there are no other elements with the class .myimg2 you could use document.get... instead of this.parentNode.get... .

With IDs instead of classes:

this.setAttribute('src',document.getElementById('myimg2').getAttribute('src'))

Note that with IDs you don't have to specify the parent node because IDs are unique to the element through the entire document.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM