RLJ Posted December 10, 2010 Share Posted December 10, 2010 Hi all, could someone pls tell me why the following javascript doesn't work? <html> <head> <script language='JavaScript'> function function1() { document.getElementsByName("txt").style.color='red'; } </script> </head> <body> <span id="span1" name="txt">some text</span><br> <span id="span2" name="txt">some more text</span><br> <span id="span3" name="txt2">some more more text</span><br> <input type="checkbox" id="check1" onchange="function1()"> </body> </html> I probably made a stupid mistake somewhere, but I just can't see where. (What I want to do is turn all text with name "txt" red) Thanks! Quote Link to comment Share on other sites More sharing options...
Adam Posted December 10, 2010 Share Posted December 10, 2010 document.getElementsByTagName returns an array, not an object. You need to use a for() loop to loop through each element it matches: var elements = document.getElementsByName("txt"); var length = elements.length; for (var i = 0; i < length; i++) { elements[i].style.color='red'; } Quote Link to comment Share on other sites More sharing options...
RLJ Posted December 10, 2010 Author Share Posted December 10, 2010 Aaaaaa I see. Thanks! Quote Link to comment Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.