Please help me with "getElementsByClass"

Hi! I am new to the forum.
And I am also new to Javascript… I am learning as I go.
I became stuck with “getElementsByClass” script.
I have got “getElementByID” to work, but found out that I needed more than 1 ID…

My site has this layout, where the right hand side DIV shows an image when a particular link in the left hand side DIV is clicked. There are multiple links on the left hand side.

[DIV1 image][DIV1 link]
[DIV2 image][DIV2 link]

Before, with IDs, I was able to display an image in [DIV1 image] by clicking on a link in [DIV1 link]. However, when I clicked on a link in [DIV2 link], it displayed in [DIV1 image] and not [DIV2 image] like I had hoped. This is because I had both [DIV image] set to the same ID…

So now I am attempting at using class. Here is my script.


var allHTMLTags = new Array();

function changeDivBG(imgName) 
{
var allHTMLTags=document.getElementsByClass(“image”);
for (i=0; i<allHTMLTags.length; i++) 
{
if (allHTMLTags[i].className==imgName) 
{
allHTMLTags[i].style.backgroundImage = "url("+imgName+")";
}
}
}

and the link in the html


<div class="image">
</div>

...
<div>
<a href="#" onclick="changeDivBGround('happy.jpg'); return false;">Happy</a>
</div>

And it doesn’t seem to work. I am using the latest version of Firefox.
The images have to be a background, because I have a transparent “template” image that goes on top.
Any help would be greatly appreciated!
Thank you very much in advance.

kf

it worked! thanks!!

Sure!

This code allows for a link to change the background image of multiple DIVs assigned with a class.


function getElementsByClassName(oElm, strTagName, strClassName)
{
    var arrElements = (strTagName == "*" && oElm.all)? oElm.all : oElm.getElementsByTagName(strTagName);
    var arrReturnElements = new Array();
    strClassName = strClassName.replace(/\\-/g, "\\\\-");
    var oRegExp = new RegExp("(^|\\\\s)" + strClassName + "(\\\\s|$)");
    var oElement;
    for(var i=0; i<arrElements.length; i++)
    {
        oElement = arrElements[i];
        if(oRegExp.test(oElement.className))
        {
            arrReturnElements.push(oElement);
        }
    }
    return (arrReturnElements)
}

function changeDivBGround(imgName)
{
var divs = getElementsByClassName(document,'div','**insert class name**');
	for (var i = 0; i < divs.length; i++)
	{
	divs[i].style.backgroundImage = "url("+imgName+")";
	}
}


<div class="**insert class name**"></div>

<a href="#" onclick="changeDivBGround('**image link**'); return false;">Click to change background</a>