Insert HTML tag to multiple selected text from different paragraph tags in html

问题: I am trying to add new HTML tags for the multi selected text from the different paragraph tag. HTML code snippet as below: <div class="sampleContent"> <p>Hell...

问题:

I am trying to add new HTML tags for the multi selected text from the different paragraph tag. HTML code snippet as below:

<div class="sampleContent">
<p>Hello</p>
<p>This one is</p>
<p>Sample Text</p>
</div>

So in above snippet I have selected "llo" text from first P tag, "This one is" text from second P tag and "Sample" text from third P tag. Now on any button selection that newly created tag should get added to all selected text so that output will be like below:

<div class="sampleContent">
<p>"He"<div id="1"> llo </div></p>
<p><div id="1"> This one is </div></p>
<p><div id="1"> Sample </div>Text</p>
</div>

So How can I add this newly created "div" element for all the selected text?

I Tried below code:

const wrapper = document.getElementsByClassName('sampleContent')[0];
wrapper.addEventListener('mouseout', event => {
const selection = window.getSelection();
 if (selection.rangeCount) {
 const replacement = document.createElement('div');
 replacement .setAttribute( "id", "1" );
 replacement.textContent = selection.toString();
 const range = selection.getRangeAt(0);
 range.deleteContents();
 range.insertNode(replacement);
}
});

But it is giving output as :

 <div class="sampleContent">
 <p>"He"<div id="1"> llo 
 This one is
 Sample 
 </div></p>
 <p>Text</p>
 </div>

回答1:

This will solve your problem.

        var count=0;
    const wrapper = document.getElementsByClassName('sampleContent')[0];
wrapper.addEventListener('mouseup', event => {
    count++;
    const original=event.target.textContent.toString();
const selection = window.getSelection();
 if (selection.rangeCount) {
 const replacement = document.createElement('div');
 replacement .setAttribute( "id", count );
 replacement.textContent = selection.toString();
 const range = selection.getRangeAt(0);
 var array=original.split("");
 array.splice(range.startOffset,range.endOffset-range.startOffset)

 var string=array.join("");
 event.target.textContent=string;
 range.deleteContents();
 range.insertNode(replacement);

}
});

Basically what I did is

  • Changed the event from mouseout to mouseup for more accurate results.
  • I applied a counter which increments on every selection event. This counter will be your id for the div. Same id of multiple elements should not be present, because of that all your results were clubbed into one div.
  • I took the whole paragraph text in a variable and removed the selected part from it and appended it back to the paragraph with the div.

Results- enter image description here

  • 发表于 2019-01-11 14:47
  • 阅读 ( 192 )
  • 分类:网络文章

条评论

请先 登录 后评论
不写代码的码农
小编

篇文章

作家榜 »

  1. 小编 文章
返回顶部
部分文章转自于网络,若有侵权请联系我们删除