HTML - DOM 元素 lang 屬性



**lang** 屬性是 HTML 元素的一個屬性,用於指定語言程式碼,例如英語為 'en',法語為 'fr',表示該元素內內容的語言。

語法

設定 lang 屬性
element.lang = lang_code;
獲取 lang 屬性
element.lang

屬性值

描述
lang_code 元素內內容的語言。

返回值

此屬性返回一個字串,包含元素 lang 屬性的值。

HTML DOM 元素 'lang' 屬性示例

以下是一些示例,展示了 'lang' 屬性的各種用法,以便更好地理解。

訪問和顯示 Lang 屬性

此示例顯示了 lang 屬性的用法,用於訪問和顯示元素的語言屬性。當我們點選“顯示 Lang 屬性”按鈕時,它會顯示應用於**<p>**元素的 'lang'(語言)屬性的值。

<!DOCTYPE html>
<html lang="en">

<body>
    <h1>HTML - DOM Element</h1>
    <h2>lang Property Example</h2> 
    <p id="ex" lang="en">This paragraph is in English.</p>
    <button onclick="displayLangAttribute()">
        Display Lang Attribute
    </button>

    <div id="output"></div>

    <script>
        function displayLangAttribute() {
            const paragraph = document.getElementById('ex');
            const langAttribute = paragraph.lang;

            const res = 
            `<p>Lang Attribute Value: ${langAttribute}</p>`;
            document.getElementById('output').innerHTML = res;
        }
    </script>
</body>

</html>   

在各個部分顯示 'lang' 屬性

此示例顯示了 lang 屬性的用法,用於訪問和顯示文件中不同部分的語言屬性。當我們點選“顯示 Lang 屬性”按鈕時,它會顯示應用於 ID 為 'exampleDIv' 的**<div>**元素的 ID 和 'lang'(語言)屬性。

<!DOCTYPE html>
<html lang="en">

<body>
    <h1>HTML - DOM Element</h1>
    <h2>lang Property Example</h2>
    <p>It displays the 'lang' attribute for both 
        english and France paragraphs.
    </p>
    <article id="article1" lang="en">
    <h2 lang="en">Introduction</h2>
    <p lang="en">
        This is the introduction paragraph in English.
    </p>
    </article>

    <article id="article2" lang="fr">
    <h2 lang="fr">Introduction</h2>
    <p lang="fr">
        Ceci est le paragraphe d'introduction en français.
    </p>
    </article>

    <button onclick="displayLangAttributes()">
        Display Lang Attributes
    </button>

    <div id="ot"></div>

    <script>
        function displayLangAttributes() {
            const art=document.querySelectorAll('article');

            let res="<p><b>Lang Attributes:</b></p>";
            art.forEach(article => {
            const articleId = article.id;
            const articleLang = article.lang;
            res+=`<p>${articleId}-Lang:${articleLang}</p>`;
            });

            document.getElementById('ot').innerHTML =res;
        }
    </script>
</body>

</html>         

支援的瀏覽器

屬性 Chrome Edge Firefox Safari Opera
lang
html_dom_element_reference.htm
廣告