elt.lang = 'fr' not working

这一生的挚爱 提交于 2019-12-13 03:03:37

问题


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 ?


回答1:


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".




回答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";


来源:https://stackoverflow.com/questions/18485948/elt-lang-fr-not-working

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!