javascripthtmlinheritancesetattributelang

Is inheritance of HTML attributes being updated when using the setAttribute() method?


I'm currently working on a semi-automatic multilingual system for websites created with Publii. Now I wanted to update the lang attribute of the site's html element according to a variable I've saved in LocalStorage.

I've put this <script> block at the end of the site's body:

<script type="text/javascript" defer>
//<![CDATA[
    const currentLang = localStorage.getItem("currentLang") || "de";
    localStorage.setItem("currentLang", currentLang);
    document.getElementsByTagName("html")[0].setAttribute("lang", currentLang);
    langChange(currentLang);
//]]>
</script>

(the langChange() method changes the language of the site's content).

I already confirmed that this successfully updates the lang attribute of the html element. But now I'm wondering if this actually does something, because even though the lang attribute gets inherited by every element on the site, I cannot verify if it actually works or if in the end just the html element has an updated lang tag and every other element persists with the old/default one.

Lastly I'm not quite sure if it makes a difference if there already is a lang tag or if the setAttribute() method needs to create a new one.


Solution

  • Yes, child elements will get updated.

    According to the MDN docs surrounding the global lang attribute, child elements without this attribute explicitly set will inherit from their parent elements, and so on.

    If an element has no lang attribute, it will inherit the lang value set on its parent node, which in turn may inherit it from its parent, and so on.

    You can also verify this works yourself by using the pseudo CSS class :lang() and making sure that targeted child elements get updated with a given CSS style whenever the html tag has it's lang attribute updated.