I was hoping to appendChild to my h2 class. I would like to be able to stick the value from my innerHTML into the end of the h2. My error message is cannot read property of appendChild of Null.
function selectMeds(element) {
//when you set the variable to element, it enables you to onclick on the thises instead of when you getElementbyId and it only finds the first one
let checkBox = element;
// let checkBox = document.getElementById("medType");
// let text = document.getElementById("text");
if (checkBox.checked == true) {
let hiddenMed = document.querySelector('.questionMed');
hiddenMed.classList.remove("hidden");
let medName = checkBox.value;
let hiddenMedQ = document.querySelector("hiddenQ");
hiddenMedQ.appendChild(medName);
} else {
let hiddenMed = document.querySelector('.questionMed');
hiddenMed.classList.add("hidden");
}
}
<div class="container question questionMed hidden">
<h2 class="hiddenQ">Did you need a refill of </h2>
<select class="form-control" id="medAmount">
<option>Select an Option</option>
<option>Yes</option>
<option>No</option>
</select>
</div>
You need to replace document.querySelector("hiddenQ");
with document.querySelector(".hiddenQ");
because hiddenQ
is a class and you need .hiddenQ
in the querySelector
. Thus, your if
condition will have this block of code
if (checkBox.checked == true) {
let hiddenMed = document.querySelector('.questionMed');
hiddenMed.classList.remove("hidden");
let medName = checkBox.value;
let hiddenMedQ = document.querySelector(".hiddenQ");
hiddenMedQ.appendChild(medName);
}
Here is an illustration of something which you are tying to achieve:
let hiddenMed = document.querySelector('.questionMed');
let hiddenMedQ = document.querySelector(".hiddenQ");
var initialH2 = hiddenMedQ.innerHTML;
function selectMeds(element) {
let checkBox = element;
if (checkBox.checked == true) {
hiddenMed.classList.remove("hidden");
let medName = checkBox.value;
hiddenMedQ.innerHTML = initialH2 +medName;
} else {
let hiddenMed = document.querySelector('.questionMed');
hiddenMed.classList.add("hidden");
hiddenMedQ.innerHTML = initialH2;
}
}
.hidden{
display: none;
}
<div class="container question questionMed hidden">
<h2 class="hiddenQ">Did you need a refill of </h2>
<select class="form-control" id="medAmount">
<option>Select an Option</option>
<option>Yes</option>
<option>No</option>
</select>
</div>
<input type="checkbox" class="medType" onclick="selectMeds(this)" value="Tylenol"><label>Tylenol</label>