You can try this approach.. (if only you've direct text node in your div)
window.getSelection().focusNode.parentElement //returns the selected element
so you can set attr like
window.getSelection().focusNode.parentElement.setAttribute('data-id', 'id-1');
You can wrap it in a 'mouseup' event with your current div
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
</head>
<body>
<div id="myDiv">
Lorem ipsum dolor sit amet, consectetur adipisicing elit. Id natus voluptatibus eum explicabo soluta excepturi?
</div>
<div id="myDiv2">
Lorem ipsum dolor sit amet, consectetur adipisicing elit. Id natus voluptatibus eum explicabo soluta excepturi?
</div>
<script>
var myDiv = document.getElementById('myDiv')
myDiv.addEventListener('mouseup', function(){
window.getSelection().focusNode.parentElement.setAttribute('data-id', 'id-1');
})
</script>
</body>
</html>
Or it is best approach to add attr to selected 'div' only, if there is many divs
var div = document.querySelectorAll('div')
for(var i = 0; i < div.length; i++){
div[i].addEventListener('mouseup', function(){
window.getSelection().focusNode.parentElement.setAttribute('data-id', 'id-1');
}, false)
}
Selectionobject? Anyway, what do you want to do if the user selects a bigger range of text that includes some from your div and some from the element before or after the div?htmland second one is modifying the result and replacing the selected node with the modified node.