Search code examples
javascriptjquerytraversal

jQuery DOM Traversing


I got the following source code, which is generated by a PHP server file:

<div class="row">
<img src="xxx.jpg" data-imgurl="xxx.jpg" width="200"/>
<img src="xxx.jpg" data-imgurl="xxx.jpg" width="200"/>
<img src="xxx.jpg" data-imgurl="xxx.jpg" width="200"/>

<div class="test"></div>

<img src="xxx.jpg" data-imgurl="xxx.jpg" width="200"/>
<img src="xxx.jpg" data-imgurl="xxx.jpg" width="200"/>
<img src="xxx.jpg" data-imgurl="xxx.jpg" width="200"/>

<div class ="test"></div>

<img src="xxx.jpg" data-imgurl="xxx.jpg" width="200"/>
<img src="xxx.jpg" data-imgurl="xxx.jpg" width="200"/>
<img src="xxx.jpg" data-imgurl="xxx.jpg" width="200"/>

<div class ="test"></div>

</div>

Now I want to track a click on any image and display the full sized image in the appropriate #test div. However I don't know, how to access the closest #test div, because this is the place where the image should append.

$('.row').on('click', 'img', function(

)};

EDIT: the clicked image should only appear in the first following .test class.. and not in all following.

Greetings


Solution

  • First of all, there should not be any duplicate id's on the page. You need to use a class instead. Then you can use like,

    $('.row').on('click', 'img', function(){
         $(this).nextUntil(".test").next().empty().append($(this).clone());
    });
    

    or

    $('.row').on('click', 'img', function(){
         $(this).nextUntil(".test").next().html($(this).clone());
    });
    

    Fiddle