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
2 Answers
Reset to default 5Look 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
版权声明:本文标题:javascript - Split text node - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1745295006a2652021.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论