Question

Let's say I have a set of simple HTML elements as follows:

<div class="metadata">I'm metadata #1</div>
<div class="content">Hello, world!</div>

<p />

<div class="metadata">I'm metadata #2</div>
<div class="content">Hello, world!</div>

My aim is to insert each div.metadata immediately after the adjacent div.content. Obviously, I can try: $("div.metadata").insertAfter("div.content"); but doing so (as expected) appends BOTH div.metadata elements to each div.content as shown in this demo.

You might think that assigning a unique ID to each div would make things simple, but 1) these tags are dynamically generated by a CMS and I'd like to avoid manually assigning IDs, and 2) there could be dozens of the same element pairs.

So, the question is, what's the most efficient way to insert after or append each div.metadata to the adjacent div.content?

Was it helpful?

Solution

$('.content').after(function() {
    return $(this).prev('.metadata');
});

FIDDLE

OTHER TIPS

$('div.content').each(function(i) {
    $(this).prev('.metadata').insertAfter($(this));
})

http://jsfiddle.net/jwhitfieldseed/h7VZd/

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top