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 ?

有帮助吗?

解决方案 3

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 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"});
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top