0

Hey all I'm a student and I need to check a div's class. This seems like it should work but it's not... Help please! :)

<script type="text/javascript">

    function findout()
        {
            alert('function works');

            var var1 = document.getElementById("div1").className;

            if (var1.value == "special")
            {
                alert("div1 has special as a style");

                document.getElementById("div1").className = '';
            }
            else
            {
                document.getElementById("div1").className = 'special';
            }

        }

    window.onload = findout();


    </script>

Edited by Reverend Jim: Fixed formatting

2
Contributors
2
Replies
3
Views
6 Years
Discussion Span
Last Post by Airshow
0

Travist,

The probelm is in these two lines:

var var1 = document.getElementById("div1").className;
if (var1.value == "special")

Change to :

var var1 = document.getElementById("div1").className;
if (var1 == "special")

or

var var1 = document.getElementById("div1");
if (var1.className == "special")

The second version has the advantage that you can reuse var1 further down the function instead of repeatedly calling document.getElementById("div1") .

Airshow

Edited by Airshow: n/a

0

A smarter way of doing this is :

function findout() {
	var myDiv = document.getElementById("div1").className;
	if(myDiv) {
		myDiv.className = (myDiv.className === "special") ? '': 'special';//toggle action
	}
}

Or even smarter :

function toggleClass(divID, className1, className2) {
	var myDiv = document.getElementById(divID).className;
	if(myDiv) {
		myDiv.className = (myDiv.className === className1) ? className2: className1;//toggle action
	}
}
toggleClass("div1", "special", "");

Airshow

Edited by Airshow: n/a

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.