Cody Smith
Cody Smith

Reputation: 2732

JS Change class of element

All I'm trying to do is toggle the class of an elements by ID when they are clicked on.

<script>

function selectLoad(id)
{
    if(document.getElementById(id).className == "load") {
        document.getElementById(id).className = "loadSelected";
    } else {
        document.getElementById(id).className = "load";
    }
}

</script>

<div class="load" id=" ... set by PHP per element ... " onclick="selectLoad(this)">

This returns an error...

Uncaught TypeError: Cannot read property 'className' of null

So I guess it doesn't like the conditional.

I'm new to JS and need help, thanks in advance.

Upvotes: 0

Views: 11867

Answers (3)

Rob Johnstone
Rob Johnstone

Reputation: 1734

I think you are passing an id that does not exist in the dom. Has the dom loaded before your javascript is executed? Move the script to the bottom of the page just before the closing html tag

EDIT: Following discussion in comments below the error is this line:

<div class="load" id=" ... set by PHP per element ... " onclick="selectLoad(this)">

it should read

<div class="load" id=" ... set by PHP per element ... " onclick="selectLoad(this.id)">

Upvotes: 2

Gabriel Petrovay
Gabriel Petrovay

Reputation: 21864

Your code is not safe because you don't check if you have the DOM element with the given id

That is why you get the error: Cannot read property 'className' of null

if(document.getElementById(id)) {
    // ... do something and do not go further.
    return;
}

And the problem is passing this when you call selectLoad. At this point, this is the DOM element, not the string that yo expect: ... set by PHP per element .... So you have to change the code accordingly.

Upvotes: 0

6502
6502

Reputation: 114461

You are passing the dom element itself (using this), not the id.

You should change the code to

function selectLoad(element)
{
    if (element.className == "load") {
        element.className = "loadSelected";
    } else {
        element.className = "load";
    }
}

Upvotes: 5

Related Questions