如何在JavaScript中为所有含特定文本的元素循环添加子元素?
问题描述
我正在通过数组值创建动态元素树形结构,通过Parent属性值与按钮文本匹配来维护层级,后续将其用作手风琴组件。目前遇到的问题是:无法为所有包含特定文本的元素创建子元素。
我已使用for循环,并尝试通过nextElementSibling插入元素,相关函数代码如下:
function appendSymptomToForm(symptom, symptomElements, container) { if (symptom.parent === 'none') { symptomForm.appendChild(container); } else { var aTags = document.getElementsByTagName("button"); var searchText = symptom.parent; var found; for (var i = 0; i < aTags.length; i++) { if (aTags[i].textContent == searchText) { found = aTags[i].nextElementSibling; found.insertBefore(container, found.nextElementSibling); } } } console.log(`Symptom ${symptom.text} appended to the form.`); }
添加子元素的核心代码行是:
found.insertBefore(container, found.nextElementSibling);
数组window.symptomData包含3个层级,每个元素根据Parent属性添加。例如第三层级B的配置为:{ depth: 3, text: '第三层级B', parent: '第二层级B', tooltip: '描述数小时后的症状' }。可以看到页面中存在多个文本为第二层级B的按钮,但第三层级元素仅被添加到最后一个匹配的按钮下方。
内容的提问来源于stack exchange,提问作者TechChef
相关产品推荐
相关产品推荐

