Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get the text of a Span element contained inside a DIV element - which was drag-dropped into another Div

I have a DIV element which is draggable, inside this DIV, I have a span element with some text.

<div draggable="true" style="border:5px solid blue; height:30px; width:150px;">
    <span>Value123</span>
</div>

This DIV does not have any ID, or Class Name. I am not allowed to add any attribute in this DIV.

I am dragging this DIV into another DIV (Drop zone).

<div id="dropzone" ondrop="drop(event)" ondragover="allowDrop(event)" 
style="border: 2px solid blue; height:200px; width:400px">

These are the two JavaScript functions.

function allowDrop(ev) {
  ev.preventDefault();
}

function drop(ev) {
    ev.preventDefault();                     
    var data = ev.dataTransfer.getData("text");
    console.log(data); // How can I get the SPAN text here ????
}

I am getting blank in the console.

Is there any way to get the span text printed in the console after the first DIV is dragged into the second div ?

Here is the code for the full HTML Page.

<html>
<head>
    <script>
      function allowDrop(ev) {
        ev.preventDefault();
      }
      
      function drop(ev) {
          ev.preventDefault();                     
          var data = ev.dataTransfer.getData("text");
          console.log(data); // How can I get the SPAN text here ????
      }
    </script>
</head>
<body>
    <div draggable="true" style="border:5px solid blue; height:30px; width:150px;">
        <span>Value123</span>
    </div>
    <br/><br/>
    <div id="dropzone" ondrop="drop(event)" ondragover="allowDrop(event)" 
    style="border: 2px solid blue; height:200px; width:400px">        
</body>    
a</html>
like image 974
Bluemarble Avatar asked Dec 04 '25 23:12

Bluemarble


1 Answers

You can use the draggable attribute to get the text:

Working snippet:

function allowDrop(ev) {
  ev.preventDefault();
}



function drop(ev) {
  var data = $('div[draggable=true]').find('span').text();
  console.log(data);
}
<script src="https://code.jquery.com/jquery-3.6.0.js"></script>
<script src="https://code.jquery.com/ui/1.13.2/jquery-ui.js"></script>




<div draggable="true" style="border:5px solid blue; height:30px; width:150px;">
  <span>Value123</span>
</div>
<br/><br/>
<div id="dropzone" ondrop="drop(event)" ondragover="allowDrop(event)" style="border: 2px solid blue; height:200px; width:400px">

For multiple draggable divs a slight change in jquery code is needed.

Check this: https://jsfiddle.net/uoLj78xw/

like image 86
Anant Kumar Singh Avatar answered Dec 07 '25 13:12

Anant Kumar Singh



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!