0

There is a div which displays HTML on a page. I can get selected text using window.getSelection(); it returns node list. Also tried window.getSelection().toString(); it returns string.

What I need is selected DOM instead of text or node list.I want to add data-child attribute when text is selected using javascript only.

so, if displayed text is <div>xyz</div>, It should become <div data-child="id-1">xyz</div> after selection.

7
  • "it returns node list" - Doesn't it return a Selection object? 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? Commented Oct 22, 2017 at 3:22
  • @nnnnnn I will discard that selection. User will be allowed to select only a complete node. Commented Oct 22, 2017 at 3:27
  • 1
    related - stackoverflow.com/q/5083682/104380 Commented Oct 22, 2017 at 8:54
  • related - stackoverflow.com/q/4176923/104380 Commented Oct 22, 2017 at 8:54
  • You are asking two entirely separate questions. first, is getting the selection as html and second one is modifying the result and replacing the selected node with the modified node. Commented Oct 22, 2017 at 9:49

1 Answer 1

2

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)
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.