Tyranicangel
Tyranicangel

Reputation: 189

changing properties of elements of a class

I am trying to change the properties of the 'im' and 'desc' class within 'img' class.I am passing the current element to the javascript functions mOver() and mDown().When I mouseover the border of the image as well as the text underneath it should change.Here is my code:

<html>
<head>
<style>
.img
    {
    margin:2px;
    border:1px solid #0000ff;
    height:90;
    width:110;
    float:left;
    text-align:center;
    }
.im
    {
    width:110px;
    height:90px;
    display:inline;
    margin:3px;
    border:1px solid #ffffff;
    }
.desc
    {
    text-align:center;
    font-weight:normal;
    width:120px;
    margin:2px;
    }
</style>
<script>
function mOver(a)
    {
    a.style.border="10px solid #0000ff";
    a.getElementByClassName("desc").innerHTML="Click on the image";
    }
function mDown(a)
    {
    a.style.border="1px solid #ffffff";
    a.getElementByClassName("desc").innerHTML="You have clicked already";
    }
</script>
</head>
<body>
<div class="img" onmouseover="mOver(this)" onmouseout="mDown(this)">
    <a target="_blank" href="abc.png">
    <img class="im" src="abc.png"></a>
    <div class="desc">ABC</div>
</div>
<div class="img" onmouseover="mOver(this)" onmouseout="mDown(this)">
    <a target="_ blank" href="def.png">
    <img class="im" src="def.png"></a>
    <div class="desc">DEF</div>
</div>
</body>
</html>

The text underneath the image isn't changing as it should have to. I think the is something wrong with the line

a.getElementByClassName("desc").innerHTML="You have clicked already";

I am relatively new to javascript so please let me know what is wrong here.Anyways thanks in advance

Upvotes: 2

Views: 102

Answers (2)

m90
m90

Reputation: 11822

The method you are trying to use is called getElementsByClassName (it expects multiple elements to be found as opposed to getElementById) and returns a Node List. Your line should therefore read:

a.getElementsByClassName("desc")[0].innerHTML="You have clicked already";

For documentation read MDN on NodeLists

Upvotes: 1

David G
David G

Reputation: 96810

It should be getElementsByClassName with an "s". And you're also supposed to mark the index of the element whose innerHTML you want to change. If you wanted to change the first element, do this:

a.getElementsByClassName("desc")[0].innerHTML = "You have clicked already";

Since arrays are 0-indexed, this changes the first element in the array returned by the method.

But if you were intending to change all the elements with that class name then you must loop:

var elements = a.getElementsByClassName("desc");

for (var i = elements.length; i--;) {
    elements[i].innerHTML = "You have clicked already";
}

Upvotes: 2

Related Questions