Matt Coady
Matt Coady

Reputation: 3856

jQuery - Moving a div to the top of it's parent

I've got a script where if a div exists I want to be at the top of it's parent div. Here's what I tried:

        if ($(".pane-bundle-hblock .field-name-field-hblock-image-right").length){
            $(".pane-bundle-hblock .field-name-field-hblock-image-right").parent().prepend($('this'));
        }

What did I get wrong?

Upvotes: 7

Views: 16368

Answers (2)

Jason P
Jason P

Reputation: 27012

$('this') selects <this></this> elements.

I would do something like this:

$(".pane-bundle-hblock .field-name-field-hblock-image-right").each(function() {
    $(this).parent().prepend(this);
});

If the element doesn't exist, the .each() won't have anything to iterate over, so you don't really need to check to see if it exists.

Upvotes: 23

jason.zissman
jason.zissman

Reputation: 2800

I don't know that 'this' has any special context within the conditional statement. You may want to be more explicit in what you're moving:

JSFiddle example: http://jsfiddle.net/BKg6z/

if ($(".pane-bundle-hblock .field-name-field-hblock-image-right").length){
    $(".pane-bundle-hblock .field-name-field-hblock-image-right").parent().prepend($(".pane-bundle-hblock .field-name-field-hblock-image-right"));
}

Upvotes: 1

Related Questions