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>

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

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

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.