如何使用.removeChild()删除具有不同ID的多个子元素?

时间:2018-02-04 08:53:27

标签: javascript html css

我正在建造一个河内解决方案塔。当用户点击带有数字的按钮时,我试图使块消失,即。当页面加载时有10个块,但是当用户点击8按钮时,我希望删除两个最大的块。

HTML:

<div class="pillon-1">
  <div id="percent-100"></div><!--
  --><div id="percent-90"></div><!--
  --><div id="percent-80"></div><!--
  --><div id="percent-70"></div><!--
  --><div id="percent-60"></div><!--
  --><div id="percent-50"></div><!--
  --><div id="percent-40"></div><!--
  --><div id="percent-30"></div><!--
  --><div id="percent-20"></div><!--
  --><div id="percent-10"></div>
</div>

按钮的标记:

<button name="button" type="submit" id="btn-8" onclick="eightBlocks();">8</button>

我到目前为止的JS,但无法使其发挥作用:

function eightBlocks() {
  const el = document.getElementsByClassName('pillon-1')[0, 1];
  el.removeChild(document.getElementById('percent-100 percent-90'));
  return false;
}

非常感谢任何帮助。

2 个答案:

答案 0 :(得分:1)

&#13;
&#13;
removeThisAfterTesting();
function removeThisAfterTesting(){
  var els = document.querySelectorAll("*[id^='percent-']");
  els.forEach(function(el){
    el.innerHTML = el.id;
  })
}

function eightBlocks() {
  document.getElementById('percent-90').remove();
  document.getElementById('percent-100').remove();
  return false;
}

Element.prototype.remove = function() {
  this.parentElement.removeChild(this);
}
&#13;
<div class="pillon-1">
  <div id="percent-100"></div><!--
  --><div id="percent-90"></div><!--
  --><div id="percent-80"></div><!--
  --><div id="percent-70"></div><!--
  --><div id="percent-60"></div><!--
  --><div id="percent-50"></div><!--
  --><div id="percent-40"></div><!--
  --><div id="percent-30"></div><!--
  --><div id="percent-20"></div><!--
  --><div id="percent-10"></div>
</div>

<button name="button" type="submit" id="btn-8" onclick="eightBlocks();">8</button>
&#13;
&#13;
&#13;

答案 1 :(得分:0)

&#13;
&#13;
function eightBlocks() {
  var $container = document.querySelector('.pillon-1')
  var $removable1 = document.querySelector('.pillon-1 #percent-100')
  var $removable2 = document.querySelector('.pillon-1 #percent-90')
  
  if ($removable1) $container.removeChild($removable1)
  if ($removable2) $container.removeChild($removable2)
}
&#13;
.pillon-1 {
  display: flex;
  flex-direction: column;
}

.pillon-1 div {
  width: 200px;
  height: 40px;
  background-color: red;
  border: 1px solid white;
}
&#13;
<div class="pillon-1">
  <div id="percent-100">100</div><!--
  --><div id="percent-90">90</div><!--
  --><div id="percent-80">80</div><!--
  --><div id="percent-70">70</div><!--
  --><div id="percent-60">60</div><!--
  --><div id="percent-50">50</div><!--
  --><div id="percent-40">40</div><!--
  --><div id="percent-30">30</div><!--
  --><div id="percent-20">20</div><!--
  --><div id="percent-10">10</div>
</div>

<button name="button" type="submit" id="btn-8" onclick="eightBlocks();">8</button>
&#13;
&#13;
&#13;