5

I want to set two attributes to the <html> tag which are:

  • dir: rtl
  • lang: ar

I've tried:

    document.documentElement.outerHTML.setAttribute("dir", "rtl");
    document.documentElement.outerHTML.setAttribute("lang", "ar");

And:

    document.setAttribute("dir", "rtl");
    document.setAttribute("lang", "ar");

But none of the two worked.

I want to do that because I'm doing a multi-languages (Arabic and English) system for my website using JavaScript.. So I want to set those two attributes incase the language selected was Arabic.

3 Answers 3

13

Remove that "outerHTML" stuff from your first example:

document.documentElement.setAttribute("dir", "rtl");
document.documentElement.setAttribute("lang", "ar");

Or even shorter:

document.documentElement.dir = "rtl";
document.documentElement.lang = "ar";
Sign up to request clarification or add additional context in comments.

Comments

3

Why not just use querySelector?

const html = document.querySelector('html')
html.setAttribute("dir", "rtl");
html.setAttribute("lang", "ar");

1 Comment

@Nisarg Thanks for finding that. Corrected.
3

Simply remove outerHTML from your first example. document.documentElement refers to the <html> element:

console.log(document.documentElement) //before setting attributes

document.documentElement.setAttribute("dir", "rtl");
document.documentElement.setAttribute("lang", "ar");

console.log(document.documentElement) //after setting attributes
<html></html>

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.