user2126833
user2126833

Reputation: 131

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.

Upvotes: 1

Views: 963

Answers (2)

Felix Kling
Felix Kling

Reputation: 816452

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.

Upvotes: 2

jahroy
jahroy

Reputation: 22692

You're passing this.parentNode to getElementById().

getElementId() expects an id string as an argument (not a DOM element).

Upvotes: 0

Related Questions