How to set HTML lang attribute dynamically?

天涯浪子 提交于 2019-12-23 10:28:51

问题


How to set HTML 'lang' attribute dynamically in a web application?

I tried using jQuery as follows to insert the 'lang' attribute:

$(document).ready(function() {
     $("html").attr("lang", language); //'language' value is retrieved from a cookie
}); 

Using console/alert, 'lang' attribute looks to be set as expected. But if you see generated source (View Source), 'lang' isn't getting set at all.

Requirement is Screen Readers must be able to recognize the language dynamically. It would be great if there is any other solution to make Screen Readers recognize the language dynamically. Thanks everyone for the comments inline!


回答1:


But if you see generated source (View Source), 'lang' isn't getting set at all.

View Source doesn't show you the generated source. It shows you the real source. If you want to change it, then you need to change it on the server before you deliver it to the browser. You can't modify it with client side JavaScript.

Your DOM changes will show up in the live DOM, which will be visible through Inspect Element.




回答2:


Can't comment yet.

I tried the snippet and it worked for me. Of course I added a string value instead of your 'language' variable.

Don't forget to import jQuery in the top menu in order for it to work in the snippet.



来源:https://stackoverflow.com/questions/35187645/how-to-set-html-lang-attribute-dynamically

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