-2

What i need is a JS function deleteSelected() That removes the elements that are in the selectedDivs array from my HTML page. What is the most effective way?

Delete selected HTML:

<div class="DRAGGABLE ui-draggable" onclick="addDevice(this)" style="position: absolute; width: 240px; height: 41px; top: 126px; left: 27px;">
  <img id="PMF00" src="/devices/AIRC1-010.gif">
</div>

JS:

function addDevice(e) {
  if ($ctrlBeingpressed == true) {
    selectedDivs.push(e);
    e.style.border = "2px dotted black";
  }
}

Apparantely there is already a post for this :/

Firebirdz
  • 11
  • 10
  • Just to be clear, are you asked us how to remove nodes from the DOM, or DOM elements that you've added to a simple JS array? Because most of the answers are for the first one. – Andy Oct 23 '13 at 09:20
  • Not remove from the array, but remove from the page. – Firebirdz Oct 23 '13 at 09:24

2 Answers2

4

If your selectedDivs array contains actual DOM elements, you can do the following:

function deleteSelected() {
   for (var i = 0; i < selectedDivs.length; i++) {
      var el = selectedDivs[i];
      el.parentNode.removeChild(el);
   }
   selectedDivs = [];
}
Artyom Neustroev
  • 8,627
  • 5
  • 33
  • 57
1

You need to use the removeChild method

for (var i = 0, len = selectedDivs.length; i< len; i++){
  var node = selectedDivs[i];
  node.parentNode.removeChild(node);
}
Gabriele Petrioli
  • 191,379
  • 34
  • 261
  • 317