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?
views:
38answers:
3
+2
A:
var element = document.createElement(tagName);
$(element).attr('foo', 'bar');
Darin Dimitrov
2010-08-17 07:47:33
Works great! Thanks
Wai Wong
2010-08-17 07:54:45
+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
2010-08-17 07:48:49
(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
2010-08-17 08:01:35
@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
2010-08-17 08:05:40
+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
2010-08-17 07:51:21