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 that createElement()
return an Element
object which has a lang
attribute .
So you can use:
lang
attribute var elt = document.createElement("i");
elt.lang = 'fr';
setAttribute()
method var elt = document.createElement("i");
elt.setAttribute('lang','fr');
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.