views:

33

answers:

2

I've got these functions to create elements and change their attributes. Could you give me an advice on how to modify them?

function create(elem) {
return document.createElementNS ? document.createElementNS("http://www.w3.org/1999/    xhtml", elem) : document.createElement(elem);
}

function attr(elem, name, value) {
 if (!name || name.constructor != String) return "";
 name = {"for": "htmlFor", "class": "className"}[name] || name;
 if (typeof value != "undefined") {
  elem[name] = value;
  if (elem.setAttribute) elem.setAttribute(name, value);
 }
 return elem[name] || elem.getAttribute(name) || "";
}

I want to get something like this create('div', {'id': 'test', 'class': 'smth'});

function create(elem, attr) {
 if (!attr) return document.createElementNS ? document.createElementNS("http://www.w3.org/1999/xhtml", elem) : document.createElement(elem);
 if (attr) {
  var el = document.createElementNS ? document.createElementNS("http://www.w3.org/1999/xhtml", elem) : document.createElement(elem);
  for (var i = 0; i < attr.length; i++) {
   attr(el, name[i], value[i]);
  }
  return el;
 }

}

Please help =]

A: 

I would recommend a javascript framework like jQuery. They already have this functionality implemented.

$("<div/>", {
"class": "test",
text: "Click me!",
click: function(){
$(this).toggleClass("test");
}
}).appendTo("body");
Eric LaForce
I think that while that is not bad advice in general, this person appears to be building a small framework of his own, possibly to learn from the experience.
Pointy
A: 

You can't iterate through an object like that:

for (var k in attrs) {
  if (attr.hasOwnProperty(k))
    attr(el, k, attrs[k]);
}

Note that I changed your "attr" variable to "attrs" so that it doesn't hide the "attr" function you've created. Also, up in your "attr" function, change the "undefined" test:

if (typeof value !== undefined)

to be a little safer. Comparisons with "==" and "!=" attempt a type conversion, which is unnecessary if you're just checking undefined.

Pointy