Gitesh Purbia
Gitesh Purbia

Reputation: 1104

Javascript how to get selected text with its font family

I am saving selected text and its range from paragraph so i can later display it selected when open html again. I have completed all task like save its range and apply again when open it again. So i am also saving the string which is selected from the paragraph and display it in a list so i can delete also, and for that i am using function like :->

var selection = window.getSelection();
var textString = selection.toString(); 

As of now it was working fine. But now i have added a multiple language in my editor. So if i save string like above the font family which is applied to selected text, its not getting display.

So i want save its font style also, so when i show selected text in list, it will render as its font style.

How can i get font family which is applied currently on selected dom. And if not font family applied on selected dom it will come from its parent.

I dont need other styles like, color , font-weight etc.

Suppose:

<span style="font-family: "Times New Roman", Times, serif;>This is<span style="font-family:Conv_DevLys_040">Test content.</span><span>

If i select "text content" then need to apply Conv_DevLys_040 font family, if select all text then need to apply both style on particular spans.

Upvotes: 1

Views: 2169

Answers (1)

gyre
gyre

Reputation: 16777

You can use window.getComputedStyle on an element to get its font family; however, this method does not work on a regular text node, so a utility function firstElementParent(node) is required to find the first immediate parent element. You can then enclose your selection text in a span with an inline font-family, and insert that HTML text wherever you want:

function getSelectionWithFont () {

  function firstElementParent (node) {
    while (!node.parentElement) node = node.parentNode
    return node.parentElement
  }

  var output = document.getElementById('output')
  
  var selection = window.getSelection()

  var htmlString = selection.isCollapsed ?
    selection.toString() :
    '<span style="font-family:' + window.getComputedStyle(
      firstElementParent(selection.anchorNode)
    ).fontFamily + '">' + selection + '</span>'
  
  document.getElementById('output').innerHTML = htmlString

}
<p id="input" contenteditable="true" style="font-family:Georgia">Lorem ipsum dot dolor sit amet...</p>

<button onclick="getSelectionWithFont()">Get Selection with Font</button>
<p id="output"></p>

Upvotes: 1

Related Questions