简体   繁体   中英

Find closing anchor tag after image

I would like to move a div to the spot right after a closing anchor tag. All I have been given is the image classname. How do I find the closing anchor tag wrapping the image?

<a href="#"><img class="cat-image" src="http://placekitten.com/200/300" title="Funky roots" /></a>

On JS Fiddle I have an example where I iterate through a list looking for an image with a certain class name. If that image exists I would like to move the '.moveMe' to after the closing anchor tag.

Unfortunately I can't modify the html. I can't add an id or class to the anchor or image tags or wrap the whole thing in a div.

HTML:

<ul class='testList'>
    <li class="listItem-0">
        <div class="moveMe"></div> <pre>
        <div class="wrapper">
            <a href="#"><img class="cat-image" src="http://placekitten.com/200/300" title="Funky roots" /></a><!-- moveMe div here -->
        </div>
        <div class="summary"></div>
        </pre>

    </li>
    <li class="listItem-1">
        <div class="moveMe"></div>  <pre>
        <div class="wrapper">
            <div></div>
        </div>
        <div class="summary"></div>
        </pre>

    </li>
    <li class="listItem-2">
        <div class="moveMe"></div>  <pre>
        <div class="wrapper">
            <a href="#"><img class="cat-image" src="http://placekitten.com/300/400" title="bigger cat pic" /></a>
        </div>
        <div class="summary"></div>
        </pre>

    </li>
</ul>

JS:

var listItems = $(".testList li");

listItems.each(function (idx, li) {
    if ($(li).find('.cat-image').length) {
        console.log('listItemContent image==>', $('pre').find('.cat-image'));  
        /*$(li).find('???? </a>  ????').append($(li).find('.moveMe'));*/
    }
    console.log($('.testList').html());
});

JS Fiddle

Try to use .after() in this context,

var listItems = $(".testList li");
var cache = null;

listItems.each(function (idx, li) {
    cache = $(li).find('.cat-image');
    if (cache.length) {
      cache.parent().after($(li).find('.moveMe'));
    }
});

DEMO

You can do this as follows:

var listItems = $(".testList li");
listItems.each(function (idx, li) {
    var jli = $(li);
    jli.find(".cat-image")
       .closest("a")
       .after(jli.find(".moveMe"));
});

which, if you like, can be reduced to a single line:

var listItems = $(".testList li");
listItems.each(function (idx, li) {
    $(li).find(".cat-image").closest("a").after($(li).find(".moveMe"));
});

http://jsfiddle.net/MBTNU/5/

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