最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

function - JavaScript - create element and set attributes - Stack Overflow

programmeradmin0浏览0评论

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("/    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("", elem) : document.createElement(elem);
 if (attr) {
  var el = document.createElementNS ? document.createElementNS("", elem) : document.createElement(elem);
  for (var i = 0; i < attr.length; i++) {
   attr(el, name[i], value[i]);
  }
  return el;
 }

}

Please help =]

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

Share Improve this question asked Jun 25, 2010 at 11:57 Denis BobrovnikovDenis Bobrovnikov 6303 gold badges10 silver badges19 bronze badges
Add a comment  | 

5 Answers 5

Reset to default 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

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.

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.

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'});

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");
发布评论

评论列表(0)

  1. 暂无评论