<!-- HTML结构 --> <ul id="test-list"> <li>JavaScript</li> <li>Swift</li> <li>HTML</li> <li>ANSI C</li> <li>CSS</li> <li>DirectX</li> </ul>
删除与web开发无关的节点
方法一:
document.querySelectorAll("#test-list li").forEach(function(e){console.log(e.innerHTML); if(['Swift','ANSI C','DirectX'].indexOf(e.innerHTML)>-1)e.remove(); });
方法二:
var li = document.getElementById("test-list") Array.from(li.children).filter(x=>!['JavaScript', 'HTML', 'CSS'].includes(x.innerHTML)).forEach(x=>li.removeChild(x))
方法三:
var web = ["JavaScript", "HTML", "CSS"]; var ul = document.getElementById("test-list"); var arrLi = ul.children; for (var item of arrLi) { if (web.indexOf(item.innerText) === -1) { ul.removeChild(item); } }
方法一跟二都比较简练。
测试:
;(function () { var arr, i, t = document.getElementById('test-list'); if (t && t.children && t.children.length === 3) { arr = []; for (i = 0; i < t.children.length; i ++) { arr.push(t.children[i].innerText); } if (arr.toString() === ['JavaScript', 'HTML', 'CSS'].toString()) { alert('测试通过!'); } else { alert('测试失败: ' + arr.toString()); } } else { alert('测试失败!'); } })();
内容摘自https://www.liaoxuefeng.com/wiki/001434446689867b27157e896e74d51a89c25cc8b43bdb3000/001435997163473d309006809fa43abbba322be3eb090a8000