javascript:读取 html 标签中的 lang 属性

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5031531/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 15:20:23  来源:igfitidea点击:

javascript: reading lang attribute in html tag

javascriptjqueryhtml

提问by HymanLeo

In <html>tag I have attribute lang. How do I reach it using .js. I want to use contains of lang as a variable. So as I understand it should start with var lang = ????

<html>标签中我有属性lang。我如何使用 .js 访问它。我想使用包含的 lang 作为变量。所以据我所知,它应该以var lang = ????

回答by Barrie Reader

In jQuery:

在 jQuery 中:

    var theLanguage = $('html').attr('lang');
    alert(theLanguage);

If you wanna fiddle: http://jsfiddle.net/NX367/

如果你想摆弄:http: //jsfiddle.net/NX367/

If you want to do it in plain Javascript, this site will explain better than I:
http://www.javascriptkit.com/dhtmltutors/domattribute.shtml

如果你想用纯 Javascript 来做,这个网站会比我解释得更好:http:
//www.javascriptkit.com/dhtmltutors/domattribute.shtml

回答by Loktar

Pure js way

纯js方式

var lang = document.getElementsByTagName("html")[0].getAttribute("lang");

http://jsfiddle.net/loktar/ZRvE6/

http://jsfiddle.net/loktar/ZRvE6/

回答by Josh Crozier

The easiest way to retrieve the langattribute is to access the langproperty on the read-only documentElementpropertyon the documentobject:

检索lang属性的最简单方法是访问对象lang的只读documentElement属性上的document属性:

document.documentElement.lang;