-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 :/

2
  • 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. Commented Oct 23, 2013 at 9:20
  • Not remove from the array, but remove from the page. Commented Oct 23, 2013 at 9:24

2 Answers 2

5

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 = [];
}
Sign up to request clarification or add additional context in comments.

4 Comments

Will onclick="addDevice(this)" provide the DOM element ?
Very strange, this works only the first time, after that it gives; TypeError: el.parentNode is null
@Firebirdz it is because elements are still in array, but not in DOM. You need to clear your selectedDivs once the method finished. Edited answer.
You are my hero Artyom Neustroev!
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);
}

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.