19

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.

1
  • If you just want to see the attributes and functions associated with $(d) do a console.log($(d)) which will print the details of the object $(d) in the firebug console. This will work only with firefox with firebug add on Commented Apr 5, 2012 at 11:26

1 Answer 1

23
// 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) );
});
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.