简体   繁体   中英

nodeName for selected text in Javascript

I am making a HTML text editor. For this,i have a div with contenteditable set to true. For making a selected text "bold",i am trying to find node of the selected text. How should i do this or is there is any other way to implement this(particular in ie).

First, please be aware that a user's selection is not directly related to a node in the DOM. Consider this HTML fragment:

<p>
    Now <b>is the time</b> for all <u>good men</u>
    to come <i>to the <em>aid</em> of their</i>
    country.
</p>

Suppose the user's selection extends from the beginning of "time" to the end of "country". There are at least 12 nodes involved:

  1. Part of a text node: "time"
  2. The end tag of a <b> node.
  3. A text node: " for all "
  4. A complete <u> node, with a child node:
    • A text node "good men"
  5. A text node: " to come "
  6. A complete <i> node, with child nodes:
    • A text node: "to the "
    • A complete <em> node, with a child node:
      • A text node: "aid"
    • A text node: " of their"
  7. Part of a text node: " country" (note, the complete text node includes a period, but the selection does not.)

So, you can't really ask for the nodeName, because there are a lot of nodes here.

You can, however, ask "What is the nodeName of a container that completely encloses the user's selection, even if it might also enclose things that are not selected?"

If that is what you want to know, you need the TextRange.parentElement() method (for IE only, other browsers would use the range.commonAncestorContainer property).

For example, in IE:

window.document.selection.createRange().parentElement().nodeName;

That gets you the nodeName, as you state in your question title. This is different from wanting to make the text bold, which you indicate in your question text. If you want to make the text bold, you probably want the TextRange.execCommand() method.

window.document.selection.createRange().execCommand('Bold', false);

And that should make the selection bold. A list of possible commands exists.

这将为您返回nodeName,但是您决定获取选定的文本:

$("your-selector-here").context.nodeName;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM