bazzlebrush
bazzlebrush

Reputation: 428

jQuery insertBefore on each instance unexpected behaviour

I have a bunch of div's with the class 'row', containing two divs 'image' and 'description'

I'm trying to make 'description' insert before 'image' in all instances.

I tried the following code which makes logical sense to me, but the outcome is very unexpected as you can see in the fiddle.

$('.row').each(function(){ //Select each row

    $('.description',this).insertBefore('.image',this);
    // For this row, put this description before this image

});

http://jsfiddle.net/bazzle/ott5tx06/

HTML

<div class="section-products">
<div class="row">
    <div class="image">
        image row 1
    </div>
    <div class="description">
        description row 1
    </div>
</div>
<div class="row">
    <div class="image">
        image row 2
    </div>
    <div class="description">
        description row 2
    </div>
</div>
<div class="row">
    <div class="image">
        image row 3
    </div>
    <div class="description">
        description row 3
    </div>
</div>

</div>

CSS

.row div{
    width:45%;
    height:100px;
    display:inline-block;
    margin-bottom:3px;
}
.image{
    background-color:red;
}
.description{
    background-color:green;
}

Upvotes: 0

Views: 47

Answers (3)

guest271314
guest271314

Reputation: 1

Try substituting jQuery object selector

$('.description',this).insertBefore($(".image", this)); 

for string selector

'.image',this 

which does not process context parameter this as .row

http://jsfiddle.net/ott5tx06/5/

alternatively using .prependTo()

$('.row').each(function(){ //Select each row   
    $('.description',this).prependTo(this);
    // For this row, put this description before this image    
});

jsfiddle http://jsfiddle.net/ott5tx06/2/

Upvotes: 1

Amit
Amit

Reputation: 46323

If you want to control the order of the div elements, try this:

$('.row').each(function(){ //Select each row

    $('.description',this).insertBefore($('.image',this));
    // For this row, put this description before this image

});

insertBefore() puts the elements in the set before the target, but you need an actual target - you can't pass a string & separate context as you do when constructing a jQuery object.

Upvotes: 0

prograhammer
prograhammer

Reputation: 20590

insertBefore needs an element as its argument.

http://jsfiddle.net/ott5tx06/4/

$('.row').each(function(){ //Select each row

    $('.description',this).insertBefore($('.image',this));
    // For this row, put this description before this image

});

Upvotes: 2

Related Questions