There are three things that I would suggest that will solve your problem:
- Pass the
event
object to your function. This contains everything about the click
event, including what element was clicked on. This means you don't have to scour the DOM.
- Do not wrap a form control with a label. This is not how labels were intended to work. Instead use something like a
section
tag.
- Form controls and their labels are automatically connected when a
for
attribute is provided. The other can be found through control.labels[0]
or label.htmlFor
. This is particularly why you want to adhere to the standard of not wrapping controls with labels
With these adjustments, and the addition of a ternary condition statement to determine what text to display, the code will look like this:
<section class="switch">
<input id="private" type="checkbox" onclick="private(event)" />
<span class="slider"></span>
</section>
<label for="private"></label>
function private(e) {
var checkBox = e.currentTarget,
label = checkBox.labels[0];
label.textContent = checkBox.checked ? "Public" : "Private";
}
Example:
function private(e) {
var checkBox = e.currentTarget,
label = checkBox.labels[0];
label.textContent = checkBox.checked ? "Public" : "Private";
}
<section class="switch">
<input id="private" type="checkbox" onclick="private(event)" />
<span class="slider"></span>
</section>
<label for="private"></label>