Search code examples
javascriptdom-events

Change Parent Class onfocus


I have a field where I want selection of one of the input boxes to change the background color of the field. My attempt was to change the html class of the parent of the input, which is the field, through a simple onfocus action, but I'm seeing no reaction.

I have the following, and have double checked the class names.

In the script:

function changefield()
{
document.getElementById(this.parentNode).className = "temp_field";
}

In the html:

<input class="type1" type="text" size="30" onFocus="changefield()">

This feels like I'm making some fairly obvious beginners' mistake, but I've already had two people play with it to no avail.


Solution

  • Two things:

    • Inside changefield, this refers to window, which does not not have a parentNode property, so you are passing undefined to getElementById.
    • Even if it had a parent node, this.parentNode would return a DOM node, while getElementById expects a string.

    A quick solution would be to just pass the DOM element you want to modify to your function:

    function changefield(element) {
        element.className = "temp_field";
    }
    

    and

    onFocus="changefield(this.parentNode)"
    

    Even if the parent node has an ID, it does not make sense to search for the node if you already have a reference to id (.parentNode).

    For more information about event handling and how to bind event handlers, have a look at the excellent articles at quirksmode.org.