34

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!

6
  • 3
    Yes it is...you can check it: $("html").attr("lang", language); alert($("html").attr("lang")): Commented Feb 3, 2016 at 21:12
  • 11
    Pure js way: document.documentElement.setAttribute('lang','test');alert(document.documentElement.getAttribute('lang')); Commented Feb 3, 2016 at 21:15
  • If you see the DOM structure (using 'view source'), 'lang' isn't getting injected. Commented Feb 3, 2016 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 :) Commented Feb 3, 2016 at 21:19
  • 2
    Use Google Chrome's Inspect feature instead and you'll see it Commented Feb 3, 2016 at 21:21

3 Answers 3

46

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

or

document.documentElement.lang = navigator.language;

Sign up to request clarification or add additional context in comments.

Comments

12

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.

Comments

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.