JavaScript - create element and set attributes
Solution 1
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
Solution 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
.
Related videos on Youtube
Denis Bobrovnikov
Updated on April 25, 2022Comments
-
Denis Bobrovnikov about 2 years
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 =]
-
Pointy almost 14 yearsI 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.