Jump to content

document.getElementsByName to change font color not working


RLJ

Recommended Posts

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!

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';
    }

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.