Home > Article > Web Front-end > How to achieve left alignment of text in JavaScript
Method: 1. Use setAttribute(), the syntax is "element object.setAttribute("style","text-align:left")"; 2. Use the textAlign attribute, the syntax is "element object.style.textAlign" ="left";".
The operating environment of this tutorial: windows7 system, javascript version 1.8.5, Dell G3 computer.
Achieve text left alignment in JavaScript
Method 1: Use setAttribute()
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <style> div{ border: 2px solid red; text-align: right; } </style> </head> <body> <div id="box">一个div元素</div><br /> <button onclick="replaceMessage()"> 让文本左对齐</a> <script type="text/javascript"> function replaceMessage() { var div = document.getElementById("box"); div.setAttribute("style", "text-align: left;"); } </script> </body> </html>
The setAttribute() method adds the specified attribute and assigns it the specified value. If this specified property already exists, the value is only set/changed.
Method 2: Use the textAlign property of the style object
The textAlign property is used to control the alignment of the text in the element. When the value is set to "left", the text can be Arrange to the left.
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <style> div{ border: 2px solid red; text-align: right; } </style> </head> <body> <div id="box">一个div元素</div><br /> <button onclick="replaceMessage()"> 让文本左对齐</a> <script type="text/javascript"> function replaceMessage() { var div = document.getElementById("box"); // div.setAttribute("style", "text-align: left;"); div.style.textAlign="left"; } </script> </body> </html>
【Related recommendations: javascript learning tutorial】
The above is the detailed content of How to achieve left alignment of text in JavaScript. For more information, please follow other related articles on the PHP Chinese website!