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>
2
Answers
You can use the
draggable
attribute to get the text:Working snippet:
Here is a simpler/scalable way of doing this without adding the ondragstart attribute on the draggable div.
Check the below code snippet. You have to set the data when drag event is fired,
drag_event.target
has the source div. Usesource_div.childNodes[1]
to get the first child and extract the data to be used. After you set the data usingdatatransfer.setData("TYPE",Value)
then you can use the data on the destination div usingdataTransfer.getData()