views:

45

answers:

4
    $('<a />').attr({
        'href': '#'
    })
    .append(
        $('<img />').attr({
            'id'    : 'img',
            'src'   : 'edit.png'
    }))
    .appendTo('body');

Is the the "right way" to go about adding <a href="#"><img src="edit.png" id="img" /></a> to the body?

Also how would I add some css onto the img?

A: 

TIMTOWTDI aside, yes, it is one way of doing it. Remember, there is no "right" right way. If it works, it means that you are on the right track.

Also, being right is relative.

mr.b
It's not entirely relative here: One way could let through invalid or broken HTML (using only `$`); `attr()` will do validation of incoming input values.
Pekka
There are several right ways, for sure. But there are certainly wrong ways as well. I really can't agree with "If it works, it's right"
David Hedlund
Perhaps I was too general. Updated to better reflect my point.
mr.b
A: 
$('<img/>').attr({
     'id'    : 'img',
     'src'   : 'edit.png'
 }).css({/* css here*/})

more on .css()

Reigel
A: 

Not really recommended to do inline styles, but an example of CSS on an image is :

<img style="display:block;" src="##.jpg" />
jos
+1  A: 

You can put all that directly into the jQuery() since version 1.4.x

$('<a />', {
    'href': '#'
})
.append(
    $('<img />', {
        'id'    : 'img',
        'src'   : 'edit.png',
        'css'   : {
            'width'  :  '100px',
            'height' :  '30px'
        }
}))
.appendTo('body');

This even works with events and data, you can say

$('<div/>', {
     id:    'myID',
     class: 'myCLASS',
     css:   {
         position: 'absolute'
     },
     click: function(e){
         alert(e.target.id);
     },
     data:  {
         foo:  'bar'
     }
}).appendTo(document.body);
jAndy
+1 - This works with events...but there's actually a bug with `data` in particular, e.g. it overwriting events when the object's extended. You'll find the order matters when specifying `data: {}` :)
Nick Craver
I know I was the one posting this on SO :), sadly the official bug report on this wasn't even assigned to anybody - yet.
jAndy