我们说我们有这个HTML。任务是创建一个函数,该函数应该使用rowSums(df, na.rm=TRUE) *NA^!rowSums(!is.na(df))
#[1] 2 NA 10
id="removeAbove"
尝试<nav class="navbar>
<div class="container">
<div class="navbar-header">
<button type="button">
<span class="sr-only">Toggle navigation</span>
</button>
<a class="navbar-brand" href="#">Project name</a>
</div>
<div id="navbar" class="navbar-collapse">
<form class="navbar-form">
<div class="form-group">
<input type="text">
</div>
<div class="form-group">
<input type="password">
</div>
<button type="submit" class="btn">Sign in</button>
</form>
</div>
</div>
</nav>
<div class="jumbotron">
<div class="container">
<h1>Hello, world!</h1>
<p>This is a template</p>
<p id="removeAbove"><a class="btn" href="#">Learn more</a></p>
</div>
</div>
,但没有解决问题。也尝试使用父母。我正在考虑遍历DOM树,当函数找到具有此ID的元素时,前面的项开始删除。但是......不知道如何用纯JS实现这一目标。
答案 0 :(得分:1)
如果您想在 removeAbove
之前移除所有元素,您需要一个循环:
removeAllBefore(document.getElementById('removeAbove'));
function removeAllBefore(el)
{
var prevEl;
while (prevEl = el.previousElementSibling)
prevEl.parentNode.removeChild(prevEl);
if (el.parentNode.tagName.toUpperCase() != 'BODY')
removeAllBefore(el.parentNode);
}
此解决方案以递归方式移除元素之前的所有内容,并在body
元素处停止。
答案 1 :(得分:1)
如果您要移除身体中除static
的元素以外的所有内容,请尝试以下操作:
id="removeAbove"
演示:
var el = document.getElementById("removeAbove");
(function removeAllChilds(el, protected) {
//Make the protected elemnt the last in the list !
el.appendChild(protected);
//Remove all child but the protected
while (el.firstChild && el.firstChild !== protected) el.removeChild(el.firstChild);
//If we reachthe body we stop
if (el.tagName.toLowerCase() === 'body') return;
//Call the function with the parent element
removeAllChilds(el.parentElement, el);
})(el.parentElement, el);
var el = document.getElementById("removeAbove");
(function removeAllChilds(el, protected) {
//Make the protected elemnt the last in the list !
el.appendChild(protected);
//Remove all child but the protected
while (el.firstChild && el.firstChild !== protected) el.removeChild(el.firstChild);
//If we reachthe body we stop
if (el.tagName.toLowerCase() === 'body') return;
//Call the function with the parent element
removeAllChilds(el.parentElement, el);
})(el.parentElement, el);