13

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 =]

5 Answers 5

3

You did pretty good but I have a solution for you that you should try that worked for me and it is quick and easier. It for the creating a element and sets attributes function.

as you mentioned:

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

here is the solution:

function create(ele, attrs) {
    //create the element with a specified string:
    var element = document.createElement(ele);

    //create a for...in loop set attributes:
    for (let val in attrs) {
        //for support in the setAttrubute() method:
        if (element.setAttribute) {
            if (element[val] in element) {
               element.setAttribute(val, attrs[val]);
            } else {
                element[val] = attrs[val];
            }
        } else {
            element[val] = attrs[val];
        }
    }

    //return the element with the set attributes:
    return element;
}

This also works with custom attributes and it property's like innerHTML too. If you also want to be sure that I know this works I have tested it and logged it on the console and seeing it on the HTML page. I tested this on Firefox.

Here's a Demo

Sign up to request clarification or add additional context in comments.

Comments

2

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.

Comments

0

A word of advice: I personally prefer the jquery way because you can add the css and events to the element directly, and refer to objects by a var name instead of the id, but... There are issues when using this method to create input elements, ie7 & ie8 don't allow you to set the type property so beware when creating a button, textbox, etc for example, jquery will throw a "type property can't be changed" error.

If the code is to be used in a browser before ie9, best use: document.createElement instead to increase compatibility.

Comments

0
export function Element(name, object = {}) {
    const element = document.createElement(name);
    for (const key in object) {
        element[key] = object[key];
    }
    return element;
}

export function Anchor(object) {
    return Element('a', object);
}

Use it like:

const anchor = Anchor({href: 'test'});

Comments

-1

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");

1 Comment

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.

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.