JavaScript DOM Scripting By Example Adding and Removing Names RSVP Checkbox

Amandeep Pasricha
Amandeep Pasricha
14,928 Points

Since when is input a child of label? They are written out as siblings in HTML.

As asked.

4 Answers

Steven Parker
Steven Parker
177,655 Points

Assuming the "input" you're talking about is the checkbox, it is attached to the DOM as a child of the label on line 15:

  label.appendChild(checkbox);

And these elements are dynamically created by the JavaScript and do not exist in the HTML code.

Amandeep Pasricha
Amandeep Pasricha
14,928 Points

Steven Parker No I get that but a label element is never a child of an input element when you write them in HTML.

Steven Parker
Steven Parker
177,655 Points

It's also not the case here. It's the input that is the child of the label.

Amandeep Pasricha
Amandeep Pasricha
14,928 Points

Steven Parker But since when is an input ever a child of a label? They are usually siblings when you write them together in HTML. That's why I was wondering why he made their relationship like that with Javascript.

Steven Parker
Steven Parker
177,655 Points

The advantage of making the input be the child of the label is that it allows you to click on the label text to change the state of the checkbox.

When they are created as siblings, you can only change the state by clicking directly on the box.

Amandeep Pasricha
Amandeep Pasricha
14,928 Points

Steven Parker So essentially it allows you to take advantage of event bubbling.

Steven Parker
Steven Parker
177,655 Points

Event propagation ("bubbling") goes from child to ancestor(s). This is different because a click on the label (parent) changes the state of the checkbox (child).

This special action of a label can also be used on peers (siblings) by using the "for" attribute of the label.

Steven Parker
Steven Parker
177,655 Points

Amandeep Pasricha — Has that answered your original question?