javascripthtmlright-to-left

How to detect text direction of element using Javascript?


What's the best way to detect the text direction of an html element using Javascript? I would expect to get either "rtl" or "ltr".

<div dir="ltr" id="foo">bar</div>

<div style="direction:ltr" id="baz">quux</div>

<div dir="ltr"><div id="jeez">whiz</div></div>

How would I test for the direction on "foo", "baz" or "jeez"?


Solution

  • getComputedStyle is available in modern browsers (IE9+ and the others). Use it like this:

    getComputedStyle(document.getElementById("foo")).direction
    

    Here's a full example:

    for (let id of ["foo", "baz", "jeez", "hello"]) {
      console.log(id, getComputedStyle(document.getElementById(id)).direction);
    }
    <div dir="ltr" id="foo">bar</div>
    
    <div style="direction:ltr" id="baz">quux</div>
    
    <div dir="ltr"><div id="jeez">whiz</div></div>
    
    <div dir="auto" id="hello">hello</div>