What is the DOM property dir?
Overview
In this shot, we’ll learn how to change the direction of text, i.e., the reading order of the text. Reading orders are of two types: rtl, which is right to left,and ltr, which is left to right (default browswer order).
We’ll use the DOM property dir to set the order or get the element’s order. The real-world example of dir is mostly seen in the Arabic websites where they write text in rtl form.
Code
We’ll write HTML code to find or set the direction of the paragraph elements, and we’ll use both ways to set the property:
- set
dirin the tag itself. - set
dirusing JavaScript.
Explanation
-
In line 5, we set a paragraph element with
id = elemfor displaying text. We will change the direction of this element. -
In line 6, we set another paragraph element with the
dirproperty set tortlfor displaying text from right to left. We have used Arabic to show a real-world example. -
In line 8, we have written a button tag, which has a function
change()binded with anonclickevent. -
In line 11, in the script tag, we have written JavaScript code to define a function
change(), which will be called by the button from the HTML page. -
In line 12, we’ll use
document.getElementById()to get the<p>element withid = elemand change the direction of this element fromltrtortl.
After running the code, we find that the property dir in the 2nd paragraph element is rendered from the right side of the window to the left, and also when we click the button click here, the 1st paragraph element changes its dir to rtl.