Question

I have a script to change the text alignment for the textarea with the id textbox1 below:

 // <![CDATA[
 function alignFix() {

 document.getElementById("textbox1").style.textAlign="left";

 }
 // ]]>

Here's the markup:

 <textarea cols="36" rows="25" readonly="readonly" id="textbox1" name="textbox" style="text-align: center;">dynamic text populates via another script unrelated to problem</textarea>

Here's the trigger:

 <select class="c9" onchange="showCenterTemplates(this); alignFix();">

It works just fine. Now I have more than one textarea I need this script to work on, so I thought it would be a simple switch from document.getElementById to document.getElementsByTagName but to my ignorance/surprise, that didn't work so well.

I've searched the questions and forums and Google, and have found examples of document.getElementsByTagName in action, but not in the manners I need it to.

It seems like when using getElementsByTagName, one must always declare a variable (can anyone confirm if this is true?) so I tried:

 // <![CDATA[
 function alignFix() {

 var textbox = document.getElementsByTagName('textarea');
 style_textbox = textbox.style;
 style_textbox.textAlign="left";
 }
 // ]]>

but with that I'm getting a style_textbox is null or not an object error when testing. Can anyone help me out please? Thanks very much in advance.

P.S. The reason for the script is because the original contents of the textareas need to be centered, but when the user begins to select templates from the <select> to populate dynamically in the <textarea> using the showCenterTemplates() script, those templates need to have left aligned text inside the <textarea>. Hope that makes sense.

Was it helpful?

Solution

getElementsByTagName returns an array of elements, so you have to loop over it:

var i,j, textbox = document.getElementsByTagName('textarea');
for (i=0, j=textbox.length; i<j; i++) {
    textbox[i].style.textAlign='left';
}

EDIT: per request in the comment, a short explanation:

  • i is incremented from 0 (zero) as long it doesn't reach the size of the array
  • textbox is the array, textbox.lenght returns its size
  • for every i (as in i is 0, i is 1 etc.) textbox[i] represents a position in the array
  • since the array is filled with HTML Elements, every position in the array is an Element, and has a style attribute
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top