appendChild到h2类

时间:2018-05-05 13:12:04

标签: javascript html appendchild

我希望将孩子附加到我的h2班。我希望能够将我的innerHTML中的值粘贴到h2的末尾。我的错误信息是无法读取null的appendChild的属性。

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 :(得分:1)

您需要将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>