Search code examples
jqueryfinddragula

Save (and pass) position (possibly to array) of elements with specific id


I am looking for a way to save elements found within a div with the specific id.

Ideally I would want to save their id`s only and the order they appear in a div. They are copied over using dragula library.

My JS that got me nowhere:

dragula([document.querySelector('.container1'), document.querySelector('.container2')], {

  copy: function (el, source) {
    return source === document.querySelector('.container1')
  },
  accepts: function (el, target) {
    return target !== document.querySelector('.container1')
  },
   removeOnSpill: true
  });

var findId = $('.container2').find(id^=n);

$('.showMeId').append(findId);

Full, working example on codepen: https://codepen.io/anon/pen/NyBwOy


Solution

  • First of all, you will need to trigger an event to run the id check. Second, ids might be a tough thing to work with when copying HTML elements since they should really be unique per page. Have you considered unique class names?

    For some reason, jquery selectors are not working with this library you are using. It could be a codepen issue or it could be an issue with draggable.

    Using vanilla js, there are two ways to accomplish the selection and display. This code should help get you on the right path to getting the DOM data you need:

    for a specific element id:

    <button id="demo" onclick="seeId()">Click</button>
    
    function seeId(){
      var idbox = document.getElementById('n3');
      document.querySelector('.showMeId').innerHTML = idbox.textContent;
    }
    

    for further manipulation of all elements, you can use javascript methods .children / .firstChild / etc

    function seeId(){
      var idboxes = document.querySelector('.container2').children;
      document.querySelector('.showMeId').appendChild(idboxes[0]);
      for(var i of idboxes){
        console.log('or do something with each node ', i);
      }
    }