4

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"?

j0k
  • 22,600
  • 28
  • 79
  • 90
chowey
  • 9,138
  • 6
  • 54
  • 84

4 Answers4

20

getComputedStyle is available in modern browsers (IE9+ and the others).

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

http://jsfiddle.net/m8Zwk/

Reference to getComputedStyle on Mozilla Developer Network

Sgnl
  • 1,808
  • 22
  • 30
Explosion Pills
  • 188,624
  • 52
  • 326
  • 405
1

Try this

document.defaultView.getComputedStyle(document.getElementById('baz'),null)['direction'];

OR

style = document.defaultView.getComputedStyle(document.firstChild,null);
console.log(style.direction);
Tamil Selvan C
  • 19,913
  • 12
  • 49
  • 70
1

@explosion-pills answer is correct. I did some more research for IE compatibility and came up with the following:

function getDirection(el) {
    var dir;
    if (el.currentStyle)
        dir = el.currentStyle['direction'];
    else if (window.getComputedStyle)
        dir = getComputedStyle(el, null).getPropertyValue('direction');
    return dir;
}

This should even work on Firefox 3.6 which requires null as the second parameter to getPropertyValue.

Since this gives more information I thought I would post it in case it helps someone.

chowey
  • 9,138
  • 6
  • 54
  • 84
0

You can simply use the style object:

console.log(document.getElementById('baz').style.direction);

DEMO

Take note that this object of the DOM only represents the in-line styles of an element, it doesn't apply to any css style sheets.

Daedalus
  • 7,586
  • 5
  • 36
  • 61
  • This doesn't work for inherited directions, such as the "jeez" div from above, or stylesheets (as you said). Inherited direction is actually the most common case. – chowey Mar 31 '13 at 03:31
  • @chowey Then I believe you would want explosion's answer. My bad for mis-interpreting what you wanted. – Daedalus Mar 31 '13 at 03:32