views:

132

answers:

2

Hi Guys,

I am trying to add a prepend of an image and then define it's attributes. Little confused as how to do this - currently I have the following but it's not working. The HTML is

<div id="testID" class="test1">
        <div id="testID2" class="test2" ></div>
    </div>

And the JS is

var test123 = somecode{}
jQuery(test123).find('#testID2').prepend('<img />').attr({
   src: 'some src.gif',
   alt: '',
   height: '60'
});

I am hoping to achieve

<div id="testID" class="test1">
  <div id="testID2" class="test2" >
      <img src='some src.gif' alt='' height='60' />
  </div>
</div>

Any Ideas?

+2  A: 

Should be:

jQuery("<img/>").prependTo("#testID2").attr({
   src: 'some src.gif',
   alt: '',
   height: '60'
});

because from your previous code, you are attaching the attributes to the container and not the img tag

Engwan
To debug this kind of thing firebug is really useful as you can see in firebug what is being added where.
matpol
hey thanks alot - just wondering if I have a "find" in there how it works ? i've update the question
Tom
Well, there shouldn't be a need to `find()` for a `#testID2` but the argument to `prependTo()` could easily be `jQuery(test123).find('#testID2')` instead of just `"#testID2"`
gnarf
yes, that is correct. But for more complex expressions i suggest you break up the code into multiple lines/expressions. var some_img = $("<img/>").attr({...}); $(test123).find("#testID2").prepend(some_img);
Engwan
+2  A: 

Engwan's answer is a simple way to achieve what you want. This is just an alternate example where the attributes are set before the <img> tag is inserting into the DOM:

jQuery(test123).find('#testID2').prepend(
  $('<img />').attr({
   'src': 'some src.gif',
   'alt': '', 
   'height': '60'
  })
);
gnarf