How to select multiple DIVs by mousedown>mousemove>mouseup (pure JS)
You can solve this by keeping an array of selected items and pushing items to it when the mouse moves over the items if the mouse is depressed.


const mainDiv = document.createElement("div");
mainDiv.style.width = "500px";
mainDiv.style.height = "500px";
document.body.appendChild(mainDiv);

const div1 = document.createElement("div");
div1.style.position = "absolute";
div1.style.top = `${50}px`;
div1.style.left = `${50}px`;
div1.style.width = "100px";
div1.style.height = "100px";
div1.style.background = "red";
mainDiv.appendChild(div1);

const div2 = document.createElement("div");
div2.style.top = `${250}px`;
div2.style.left = `${250}px`;
div2.style.width = "100px";
div2.style.height = "100px";
div2.style.background = "green";
div2.style.position = "absolute";
mainDiv.appendChild(div2);


!(() => {
  let selection = [];
  let selecting = false;
  function beginSelection(e) {
    selection = [];
    selecting = true;
    checkSelection(e);
  }
  function mouseMove(e) {
    checkSelection(e);
  }
  function mouseUp(e) {
    selecting = false;
    if (selection.length) {
      console.log("selection: ", selection); // access selection before reset
      selection = [];
    } else {
      // no selection
    }
  }
  function checkSelection(e) {
    if (!selecting) {
      return; // ignore
    }
    const selected = e.target.parentNode === mainDiv && e.target;
    if (selected && !selection.includes(selected)) {
      selection.push(selected);
    }
  }
  mainDiv.addEventListener("mousedown", beginSelection);
  mainDiv.addEventListener("mousemove", mouseMove);
  window.addEventListener("mouseup", mouseUp);
  
})();




I'm trying to make a selection of elements when I click on empty point and move pointer.
In this example I'm expecting to get selection of two elements:

I've tried range and selection, but not with the proper result.


const mainDiv = document.createElement("div");
mainDiv.style.width = "500px";
mainDiv.style.height = "500px";
document.body.appendChild(mainDiv);

const div1 = document.createElement("div");
div1.style.position = "absolute";
div1.style.top = `${50}px`;
div1.style.left = `${50}px`;
div1.style.width = "100px";
div1.style.height = "100px";
div1.style.background = "red";
mainDiv.appendChild(div1);

const div2 = document.createElement("div");
div2.style.top = `${250}px`;
div2.style.left = `${250}px`;
div2.style.width = "100px";
div2.style.height = "100px";
div2.style.background = "green";
div2.style.position = "absolute";
mainDiv.appendChild(div2);

mainDiv.onmousedown = function(event) {
  function onMouseMove(event) {
    //add divs to selection
  }
  mainDiv.addEventListener('mousemove', onMouseMove);

  mainDiv.onmouseup = function() {
    console.log("selected divs")
  }
}



