HTML DOM dir property


The HTML DOM dir property is used for changing an element’s text direction from default left to right to right to left or auto. The dir property is used for setting and returning the dir attribute value of an element. The returned dir attribute value is of type string.

Syntax

Following is the syntax for −

Setting the dir property −

HTMLElementObject.dir = "ltr|rtl|auto"

Here, ltr=left to right text direction and it is the default text direction., rtl=right to left text direction, auto=text direction is based on content here and is usually figured by the web browser.

Example

Let us look at an example for the HTML DOM dir property −

Live Demo

<!DOCTYPE html>
<html>
<body>
<h2>HTML DOM dir property</h2>
<p id="Sample">This is a sample text</p>
<button onclick="changeDir()">Change Dir</button>
<script>
   function changeDir() {
      document.getElementById("Sample").dir = "rtl";
   }
</script>
<p>Clicking on the above button will change the text direction</p>
</body>
</html>

Output

This will produce the following output −

On clicking the “Change Dir” button −

We have first created a button “Change Dir” that will execute the changeDir() function when clicked by the user −

<button onclick="changeDir()">Change Dir</button>

The changeDir() function gets the paragraph element using the getElementById() method and sets its dir property value right to left. This displays the text from right to left −

function changeDir() {
   document.getElementById("Sample").dir = "rtl";
}

Updated on: 20-Feb-2021

93 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements