Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to change Html lang attribute from lang="en" to lang="ar" using JavaScript

welcome I searched a lot here for a solution to my question and unfortunately I couldn't find a definitive answer. I tried these answers on this question How to set HTML lang attribute dynamically? but it didn't work for me.

I created language switch button between English as default and Arabic as second language and it works fine in changing the direction of my html page from left to right because the second language is Arabic, but the attribute (lang="en") in tag does not change to (lang="ar") When the page is turned to the right, assuming that the page content will be in Arabic. Kindly Help me to implement this function. please review the attribute lang on changing to RTL I want when I press the converter button the value of attribute lang change from en to ar. Thank You all,

(function ($) {
  "use strict";
  
$(".direction_switch button").click(function () {
    $("body").toggleClass(function () {
      return $(this).is(".rtl, .ltr") ? "rtl ltr" : "rtl";
    });
  });
  
  })(window.jQuery);
.ltr {
  direction: ltr;
}

.rtl {
  direction: rtl;
}
ul {
  list-style: none;
}
.menu {
  display: block;
}
.menu ul {
  display: inline-flex;
}
.menu ul li {
  padding: 0 10px;
}
body.ltr .demo-ltr {
  display: none;
}
body.ltr .demo-rtl {
  display: block;
}
body.ltr .demo-rtl button {
  background-color: transparent;
  color: #000;
  border: 1px solid;
  padding: 0px 10px;
}
body.rtl .demo-rtl {
  display: none;
}
body.rtl .demo-ltr {
  display: block;
}
body.rtl .demo-ltr button {
  background-color: transparent;
  color: #000;
  border: 1px solid;
  padding: 0px 10px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<!DOCTYPE html>
<html lang="en">

  <head>

  </head>

  <body class="ltr">
    <nav class="menu">
      <a href="">Logo</a>
      <ul>
        <li><a href="">Home</a></li>
        <li><a href="">Abou</a>t</li>
        <!-- page-direction -->
        <div class="page_direction">
          <div class="demo-rtl direction_switch"><button class="rtl">RTL</button>
          </div>
          <div class="demo-ltr direction_switch"><button class="ltr">LTR</button>
          </div>
        </div>
        <!-- page-direction end -->
      </ul>
    </nav>
  </body>

</html>
like image 297
Hatem Frere Avatar asked Nov 24 '25 20:11

Hatem Frere


1 Answers

document.documentElement.setAttribute('lang', 'AR');

also

document.documentElement.lang = 'AR'

Attention this;

<script>Code Here</script>

HTMLElement.lang Description

like image 129
Burak Odabaş Avatar answered Nov 26 '25 08:11

Burak Odabaş



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!