views:

38

answers:

3

If I create a new DOM element with Javascript document.createElement, is there a way to use jquery function attr() to change the element's attribute?

+2  A: 
var element = document.createElement(tagName);
$(element).attr('foo', 'bar');
Darin Dimitrov
Works great! Thanks
Wai Wong
+1  A: 

you can use javascript like :

var link = document.createElement('a');
link.setAttribute('href', 'mypage.htm');

or jquery

$(link).attr('href', 'mypage.htm');
Haim Evgi
(for the first method) if you will add an event (like onclick). maybe you should just uselink.onclick instead of link.setAttributesource = http://justinfrench.com/notebook/javascript-setattribute-vs-ie
yilmazhuseyin
@yilmazhuseyin: Yeah, that's why I always recommend to use [DOM properties](http://www.w3.org/TR/DOM-Level-2-HTML/html.html#ID-642250288) over `setAttribute`.
CMS
thanks for the enlightening remark
Haim Evgi
+1  A: 

Of course you can, but compare:

var element = document.createElement('input');

$(element).attr('type', 'button');

// vs.

element.type = 'button';

IMO I would simply use the second approach, staying away from the IE's buggy element.setAttribute method.

CMS