gpt4 book ai didi

javascript - appendChild 到 h2 类

转载 作者:行者123 更新时间:2023-11-30 20:32:30 24 4
gpt4 key购买 nike

我希望将 appendChild 添加到我的 h2 类(class)中。我希望能够将 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>

最佳答案

您需要将 document.querySelector("hiddenQ"); 替换为 document.querySelector(".hiddenQ"); 因为 hiddenQ是一个类,您需要 querySelector 中的 .hiddenQ。因此,您的 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>

关于javascript - appendChild 到 h2 类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50189835/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com