appendChild к классу h2 - PullRequest
0 голосов
/ 05 мая 2018

Я надеялся добавить ребенка в мой класс h2. Я хотел бы иметь возможность вставить значение из моего innerHTML в конце h2. Мое сообщение об ошибке не может прочитать свойство 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>

1 Ответ

0 голосов
/ 05 мая 2018

Вам нужно заменить document.querySelector("hiddenQ"); на document.querySelector(".hiddenQ");, потому что hiddenQ - это класс, и вам нужно .hiddenQ в querySelector. Таким образом, ваше if условие будет иметь этот блок кода

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);
}

Вот иллюстрация того, чего вы пытаетесь достичь:

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>
...