Reputation: 307
I am trying to pass an object literal to the .attr() method in jQuery to automate creating a DOM element. The problem is when there is more than one attribute to set it fails.
var atts = {'type':'text', 'id':'#inputBox'};
createElem('<input></input>', '#divToAppendTo', atts);
function createElem(typeOfField, fldToAppendTo, atts){
// this works when there is only one attribute to set, but fails when there is more than 1
jQuery(typeOfField, atts).appendTo(fldToAppendTo);
}
Any ideas?
Upvotes: 2
Views: 1398
Reputation: 140210
Get rid of your code and use this instead:
$( "<input>", {type:'text', id:'inputBox'} ).appendTo("#divAppendTo")
Note that for jQuery constructor all the following are equivalent and trigger the document.createElement
optimization path:
"<input></input>"
"<input/></input>"
"<input/>"
"<input>"
// Plus infinite different combinations of whitespace
Upvotes: 1
Reputation: 171679
You mentioned attr()
method in thread title , but aren't using it
Try:
function createElem(typeOfField, fldToAppendTo, atts){
// this works when there is only one attribute to set, but fails when there is more than 1
jQuery(typeOfField).attr( atts).appendTo(fldToAppendTo);
}
Upvotes: 0