DataTransfer: getData() method
        
        
          
                Baseline
                
                  Widely available
                
                
              
        
        
        
          
                
              
                
              
                
              
        
        
      
      This feature is well established and works across many devices and browser versions. It’s been available across browsers since July 2015.
The DataTransfer.getData()
method retrieves drag data (as a string) for the specified type.
If the drag operation does not include data, this method returns an empty
string.
Example data types are text/plain and text/uri-list.
Syntax
getData(format)
Parameters
- format
- 
A string representing the type of data to retrieve. 
Return value
A string representing the drag data for the specified format. If the drag operation has no data or the operation has no data for the specified format, this method returns an empty string.
Note that DataTransfer.getData() may not return an expected value, because it only allows reading and writing data for specified events. During the dragstart and drop events, it is safe to access the data. For all other events, the data should be considered unavailable. Despite this, the items and their formats can still be enumerated.
Examples
This example shows the use of the DataTransfer object's
getData() and
setData() methods.
HTML
<div id="div1">
  <span id="drag" draggable="true">drag me to the other box</span>
</div>
<div id="div2"></div>
CSS
#div1,
#div2 {
  width: 100px;
  height: 50px;
  padding: 10px;
  border: 1px solid #aaaaaa;
}
JavaScript
const div1 = document.getElementById("div1");
const div2 = document.getElementById("div2");
const dragElement = document.getElementById("drag");
dragElement.addEventListener("dragstart", drag);
div1.addEventListener("dragover", allowDrop);
div2.addEventListener("dragover", allowDrop);
div1.addEventListener("drop", drop);
div2.addEventListener("drop", drop);
function allowDrop(allowDropEvent) {
  allowDropEvent.target.style.color = "blue";
  allowDropEvent.preventDefault();
}
function drag(dragEvent) {
  dragEvent.dataTransfer.setData("text", dragEvent.target.id);
  dragEvent.target.style.color = "green";
}
function drop(dropEvent) {
  dropEvent.preventDefault();
  const data = dropEvent.dataTransfer.getData("text");
  dropEvent.target.appendChild(document.getElementById(data));
  dragElement.style.color = "black";
}
Result
Specifications
| Specification | 
|---|
| HTML> # dom-datatransfer-getdata-dev> | 
Browser compatibility
Loading…