Question

I have a simple UL with all LI's having class="event".

The following jQuery is not working as expected.

$('#calendar-feed li.event').each(function() {
    $(this).find('h3').appendTo('h4');
});

I'd like to take the only h3 in every LI and append it to the only h4 in that LI.

Currently it is taking all the H3s and cloning them into each H4.

Is my syntax just wrong or am I thinking about this the wrong way?

Was it helpful?

Solution

Do this, because the appendTo is a new selector which can contain anything within the page. So you were selecting all H4 within the page and added them to the LI h3.

$('#calendar-feed li.event').each(function() {
    $(this).find('h3').appendTo($(this).find('h4'));
});

OTHER TIPS

I think you need to get the correct h4 inside the loop, something like this:

$('#calendar-feed li.event').each(function() {
    var h4 = $(this).find('h4');
    $(this).find('h3').appendTo(h4);
});

Here is a working example

It makes no sense appending an <h3> INTO <h4>.

I guess what you want is to place <h3> AFTER <h4>, swapping their positions (although it still makes less sense if you're using these tags, but anyway)

$('#calendar-feed li.event h3').each(function (i, h3) {
    var $h3 = $(h3);
    $h3.after($h3.closest('li').find('h4'));
});

Alternatively if you want the <h3> guaranteed to be the last element in each <li>, then do this

$('#calendar-feed li.event h3').each(function (i, h3) {
    var $h3 = $(h3);
    $h3.appendTo($h3.closest('li'));
});

DEMO: http://jsfiddle.net/terryyounghk/sN7Mf/

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