I work in the context of a Firefox extension.

Issue

I'm trying to create a new element with a specific lang attribute. I tried the method elt.lang = 'zh' given in How to create HTML element with lang attribute in JavaSript? doens't work. The element is created but without the lang attribute.

Not working as expected code

var wrapper = document.createElement("span");
  var zh = document.createElement("i");
    zh.textContent = symbol;
    zh.lang= "zh-cmn"; // <-- -- -- -- -- -- --
  var srcText = document.createTextNode('blablabla');
wrapper.appendChild(zh);
wrapper.appendChild(srcText);

Working as expected code

However when I use the Element.setAttribute() method it works fine:

zh.setAttribute('lang','zh');

Why the elt.lang/dot-notation approach not working ?

有帮助吗?

解决方案 2

Issue

The problem was related to the environment (i.e. an extension). I was in a XUL context so using createElement() create a XUL element which don't have a lang attribute.

So to fix problem and other (no way to select inserted text), I had to force the XHTML namespace with createElementNS(ns, elt).

Code

var nsXHTML = "http://www.w3.org/1999/xhtml";
var wrapper = document.createElementNS(nsXHTML, "span");
var zh = document.createElementNS(nsXHTML, "i");
zh.lang= "zh-cmn";

其他提示

Not all possible HTML attributes are reflected as javascript setters / getters. For instance, https://developer.mozilla.org/en-US/docs/Web/API/Node definitely lists textContent, but not lang. I would suggest always using setAttribute / getAttribute, except for possibly the most basic attributes such as "src" or "href".

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top