Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

create JQuery object by passing DOM object?

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.

like image 459
Murvinlai Avatar asked Oct 25 '09 20:10

Murvinlai


1 Answers

// 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) );
});
like image 63
karim79 Avatar answered Oct 13 '22 21:10

karim79