Search code examples
javascriptattributesfirefox-addonlang

elt.lang = 'fr' not working


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 ?


Solution

  • 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";