Rouge
Rouge

Reputation: 4239

Jquery insertBefore issue

I am having troubles getting my insert element task done here and I have been spending hours for it.

I tried to insert elements by class name when user clicks the button. I also have css setup in the script. My problem is that only the first element has css property but not the rest. Can anyone help me about it? Thanks so much!

Jquery

  //when users clicks the button

   var imgForClass = $("<img src='images/anim.gif' class='imgAbs'>");

   var cssProp = {'position':'absolute',
                       'z-index':99,
                       'top': topPos,  //topPos is the position that the element I want to attach to.
                       'left': leftPos //leftPos is the position that the element I want to attach to.
            }

   //detect if the element has id of 'cons'
   if($element.is('#cons'){                
               imgForClass.insertBefore('.conElement');
               imgForClass.css(cssProp) 
    }

Html

<div>
<img src='a.jpg'/>
<img id='cons' src='b.jpg'/>
</div>      

//the new element will be inserted here but only the first element has css property(z-index...etc)
<div class='conElement'>
<img src='b.jpg'/>
</div>      

//the new element will be inserted here but has no css property(z-index...etc)
<div class='conElement'>
<img src='b.jpg'/>
</div>      

//the new element will be inserted here but has no css property(z-index...etc)
<div class='conElement'>
<img src='b.jpg'/>
</div>      

//the new element will be inserted here but has no css property(z-index...etc)
<div class='conElement'>
<img src='b.jpg'/>
</div>   


...more <div>         

Upvotes: 0

Views: 220

Answers (2)

Ilia Frenkel
Ilia Frenkel

Reputation: 1977

I think this will do:

if($element.is('#cons'){                
    imgForClass.insertBefore('.conElement').css(cssProp);
}

Upvotes: 0

OJay
OJay

Reputation: 4921

I think the problem here is that you are expecting the imgForClass variable after the insertBefore() method call to now be a reference to all of the newly inserted img tags, and I believe it is only holding a reference to the first one. So perhaps something like the following would help you

if($element.is('#cons'){                
               imgForClass.insertBefore('.conElement');
               $('.imgAbs').css(cssProp);
} 

on a side note, its not good practice to have multiple elements on a page with the same ID as you are doing with all the

<img id='cons' src='b.jpg'/>

Upvotes: 1

Related Questions