Roland
Roland

Reputation: 33

JavaScript LTR/RTL detection on a DOM element

How can I detect the text direction of an element?

The text direction can be set in a HTML document to any element or a parent thereof. You can do that through the elements dir property, or through the direction property of CSS. And the browser can be set to LTR or RTL as a whole as well, so you might have RTL styling without any property set.

<body dir=rtl>
  <div dir=ltr style="direction:rtl" class="western">
    <span id=whatAmI></span>
  </div>
</body>

Now how can I detect, in javascript, whether the whatAmI span is RTL or LTR aligned?

I'm thinking of adding an invisible element and requesting its position, but it feels like there must be better ways to get this info.

Upvotes: 3

Views: 1790

Answers (1)

Or Assayag
Or Assayag

Reputation: 6336

getComputedStyle(document.getElementById('whatAmI')).direction;

Upvotes: 3

Related Questions