admin管理员组

文章数量:1418687

I have div[contenteditable=true]. Text can be bold/italic/underline.

<div contenteditable=true>
  <b>Text</b>
</div>

I need to split text node to 2 blocks:.

<div contenteditable=true>
  <b>Te</b><b>xt</b>
</div>

Just for Chrome and Safari.

I have div[contenteditable=true]. Text can be bold/italic/underline.

<div contenteditable=true>
  <b>Text</b>
</div>

I need to split text node to 2 blocks:.

<div contenteditable=true>
  <b>Te</b><b>xt</b>
</div>

Just for Chrome and Safari.

Share Improve this question asked Sep 7, 2012 at 13:50 user1050438user1050438 4
  • why do you need to split the text in such a way? What are you trying to acplish? – jackwanders Commented Sep 7, 2012 at 13:53
  • Since your request doesn't change the rendering of the text, what problem are you really trying to solve? – jfriend00 Commented Sep 7, 2012 at 14:00
  • @Alnitak because there's always more than one way to skin a cat. Depending on why he wants to split one b tag into two, there might be a more appropriate solution. Context is important; this site is about helping solve people's problems, not just throwing code snippets at anyone who asks for them. – jackwanders Commented Sep 7, 2012 at 14:00
  • I'm not using jQuery. We have segments, user type some text and can split it. If text was formatted and I try split segment text formatting is reset. – user1050438 Commented Sep 10, 2012 at 9:45
Add a ment  | 

2 Answers 2

Reset to default 5

Look at Text.splitText.

var b = document.querySelectorAll("div[contenteditable='true'] > *")[0];
var p = b.parentNode; // the element's parent
var t = b.firstChild; // the textNode content

var newText = t.splitText(2);    // splits the node, leaving it in place
var copy = document.createElement(b.tagName);  // make another wrapper
copy.appendChild(b.lastChild);  // move second text into the copy
p.insertBefore(copy, b.nextSibling);  // put the copy into the DOM.

See http://jsfiddle/alnitak/JbEnL/

As you specified Chrome and Safari I've used querySelectorAll to find the initial inner DOM element.

Here's a way to take the first bold tag in the div, and split the text in it among two bold tags:

Initial HTML:

<div id="target" contenteditable=true>
  <b>Text</b>
</div>​

Code:

var bold = document.getElementById("target").getElementsByTagName("b")[0];
var txt = bold.innerHTML;
bold.innerHTML = txt.substr(0,2);
var newBold = document.createElement("b");
newBold.innerHTML = txt.substr(2);
bold.parentNode.insertBefore(newBold, bold.nextSibling);

Working demo: http://jsfiddle/jfriend00/KsPrg/

本文标签: javascriptSplit text nodeStack Overflow