views:

686

answers:

1

So, let say I have this:

var d = document.createElement('div');
d.id = "whatever";`

So, d is the DOM object,

how can I create or convert it into jQuery object?

e.g. $(d) ???

and, how to 'read' all attributes of the jQuery object? just like the var_dump of PHP.

+15  A: 
// create a jQuery-boosted div
$div = $('<div></div>');
$div.attr('id','someId');
alert($div.attr('id'));

// to get the DOM element:
var div = $div[0];

// or
var div = $div.get(0);

or just wrap the dom element in $() as you suggested:

$(d).attr('id','someId');
$(d).blah();

Use attr to get/set element attributes. I'm not sure if there's a one-liner that can dump all of an element's attributes and their respective values (firebug serves that purpose for me), but you can create an array with all the attribute names you're interested in, and do something like:

var attr = ['name', 'id', 'src', 'foo'];
var len = attr.length;
for (var i = 0; i < len; i++) 
    alert($(d).attr(attr[i]));

or using $.each:

$.each(['name', 'id', 'src', 'foo'], function(i,val) {
    alert( 'Attribute: ' + val + ' Value: ' + $(d).attr(val) );
});
karim79
Thanks. It is helpful. :)
Murvinlai