获取HTML元素的隐式lang属性

时间:2016-02-16 20:26:47

标签: javascript iso lang

假设您有一个HTML页面,其中包含不同语言的部分,如下所示:

<html lang=en>
<div lang="th">
  <p id="test1">ไทย</p>
</div>
<p id="test2">Implicitly English</p>
<div lang="en-CA">
  <p id="test3">As Canadian as possible under the circumstances</p>
</div>
<p lang="en-AU"id="test4">Explictly Aussie</p>
</html>

是否有直接的方法来发现哪种特定语言代码适用于给定的HTML元素?类似的东西:

// pseudo-code
var lang = myElement.getLang()

这里似乎是一个非常迂回的解决方案:

function getLang(element) {
  var lang = element.getAttribute("lang")

  if (!lang) {
    var elements
      , languages
      , language
      , ii
      , selector

    // Find all elements with an explicit lang attribute
    elements = [].slice.call(document.querySelectorAll("*[lang]"))

    // Determine which languages are present
    languages = []
    for (ii in elements) {
      lang = elements[ii].getAttribute("lang")
      if (languages.indexOf(lang) < 0) {
        languages.push(lang)
      }
    }

    lang = "" // reset

    for (ii in languages) {
      language = languages[ii]
      selector = ":lang(" + language + ")"
      elements = [].slice.call(document.querySelectorAll(selector))

      if (elements.indexOf(element) > -1) {
        if (lang.length < language.length) {
          lang = language
        }
      }
    }
  }

  return lang
}

有更明显的方法吗? jsFiddle

1 个答案:

答案 0 :(得分:1)

我使用以下代码更新了您的小提琴,您可以在此代码段中运行该代码。这大大简化了它。

function getLang(elem) {
  var lang = "";
  if (elem) {
    var elements = [];
    var queryResult = document.querySelectorAll("[lang]");
    try {
      //Wrapping in a try catch block to handle unsupported browsers.
      elements = [].slice.call(queryResult);
    } catch (error) {
      for (var i = 0, len = queryResult.length; i < len; i++) {
        elements.push(queryResult[i]);
      }
    }
    if (elements.length > 0) {
      //Find in the NodeList where the element is either itself or the first parent with lang attribute of the given element.
      var matches = elements.filter(function(e) {
        return e === elem || e.contains(elem);
      }); //ES2015 -> elements.filter(e => e === elem || e.contains(elem));
      var match = matches.length > 0 ? matches[matches.length - 1] : matches[0];
      lang = match.lang ? match.lang : lang;
    }
  }
  return lang;
}

var result = getLang(document.querySelector("#test1")) + " ";
result += getLang(document.querySelector("#test2")) + " ";
result += getLang(document.querySelector("#test3")) + " ";
result += getLang(document.querySelector("#test4"));

alert(result);
<body lang=en>
  <div lang="th">
    <p id="test1">ไทย</p>
  </div>
  <p id="test2">Implicitly English</p>
  <div lang="en-CA">
    <p id="test3">As Canadian as possible under the circumstances</p>
  </div>
  <p lang="en-AU" id="test4">Explictly Aussie</p>
</body>