0

I got the following HTML:

<div id="editable_phrase"> 
   <span data-id="42">My</span> 
   <span data-id="43">very</span> 
   <span data-id="1">first</span> 
   <span data-id="21">phrase</span>
</div>

and I need to get the data-id attributes when I select (highlight) with a mouse these words. I use the following code:

var data = window.getSelection().getRangeAt(0).cloneContents();//this gets the data for all selected words 
console.log(data);

It works fine except that when I select last word phrase, it selects only text without html contents. Any ideas how to fix that? I can use jQuery.

If I select 2 or 3 words, I need to get their data-ids respectively to each word, as it is with getRangeAt(0).cloneContents(). The problem is only with the last word, which does not return HTML code.

Thank you.

2 Answers 2

1

EDIT:

There has been a similar thread before, here is a working solution:

https://jsfiddle.net/hallleron/wg1pbwbf/2/

Basically you loop through the siblings in the selection to get each value and then parse the array as string to display it in my result paragraph for better visuals.

ORIGINAL:

If you want a jQuery-free version, here is a fiddle: https://jsfiddle.net/hallleron/wg1pbwbf/

The whole Javascript Part is the following:

document.getElementById('editable_phrase').addEventListener("click", getDataId);

function getDataId(){
     console.log(window.getSelection().anchorNode.parentElement.attributes[0].nodeValue);
}

So every time the event listener detects a click, it gets the selected text/span and extracts its data-id attribute from the object.

Sign up to request clarification or add additional context in comments.

2 Comments

It select only one element, though I highlight 2 or 3. If I select 3 elements, I need to get all their data-ids
Ah okay sorry I got that wrong... I'll try to update the code as soon as possible.
1

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<div id="editable_phrase"> 
    <span data-id="42">My</span> 
    <span data-id="43">very</span> 
    <span data-id="1">first</span> 
    <span data-id="21">phrase</span>
</div>
<script>
    $('#editable_phrase').on('click','span',function(){
        var res = $(this).attr('data-id');
        alert(res);
    })
</script>

3 Comments

You could also use $(this).data("id"), but I'm not sure which is faster.
Are you not going to say why that helps or is it a secret?
Does it work with selection? If I select (highlight) 3 words in a row I need to get their 3 data-ids

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.