28

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!

Reg Edit
  • 6,719
  • 1
  • 35
  • 46
Xplora
  • 837
  • 3
  • 12
  • 24
  • 3
    Yes it is...you can check it: `$("html").attr("lang", language); alert($("html").attr("lang")):` – Hackerman Feb 03 '16 at 21:12
  • 10
    Pure js way: `document.documentElement.setAttribute('lang','test');alert(document.documentElement.getAttribute('lang'));` – Hackerman Feb 03 '16 at 21:15
  • If you see the DOM structure (using 'view source'), 'lang' isn't getting injected. – Xplora Feb 03 '16 at 21:15
  • 3
    @Xplora...that is not how it is supposed to work...remember that your are changing the DOM programmatically...when you see the source via View Source, you see the original html structure :) – Hackerman Feb 03 '16 at 21:19
  • 2
    Use Google Chrome's Inspect feature instead and you'll see it – phenxd Feb 03 '16 at 21:21

3 Answers3

35

document.documentElement.setAttribute('lang', navigator.language);

or

document.documentElement.lang = navigator.language;

ShortFuse
  • 5,970
  • 3
  • 36
  • 36
10

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.

Quentin
  • 914,110
  • 126
  • 1,211
  • 1,335
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.

phenxd
  • 689
  • 4
  • 17