Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaScript - create element and set attributes

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

like image 421
Denis Bobrovnikov Avatar asked Jun 25 '10 11:06

Denis Bobrovnikov


People also ask

How do you set an element attribute?

setAttribute() Sets the value of an attribute on the specified element. If the attribute already exists, the value is updated; otherwise a new attribute is added with the specified name and value. To get the current value of an attribute, use getAttribute() ; to remove an attribute, call removeAttribute() .

Can you set multiple attributes in JavaScript?

To set multiple attributes at once on an element: Add the attribute names and values to an object. Use the Object. keys() method to get an array of the object's keys.

What method allows us to add an attribute to a DOM element?

The setAttribute() method sets a new value to an attribute.


2 Answers

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

like image 90
Harry Smart Avatar answered Oct 21 '22 18:10

Harry Smart


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.

like image 30
Pointy Avatar answered Oct 21 '22 19:10

Pointy