I want to create a new element with a lang
attribute.
Can I do that as a one-liner ? If not what is the shortest method ?
I want to create a new element with a lang
attribute.
Can I do that as a one-liner ? If not what is the shortest method ?
The shortest you can do is a two-liner:
var div = document.createElement('div');
div.lang = 'en';
As Blender says, you have to have two statements (which would traditionally be written in two lines).
You can, of course, give yourself a helper function to do it in one:
function createElement(type, props) {
var key;
var elm = document.createElement(type);
if (props) {
for (key in props) {
elm[key] = props[key];
}
}
return elm;
}
Usage:
var newSpan = createElement("span", {lang: "en"});
Playing with the
Firebug
console, I found thatcreateElement()
return anElement
object which has alang
attribute.So you can use:
lang
attributesetAttribute()
method