Dom Nodes actions, how to remove tags that wrap my choice?

I am trying to explain my “problem” to you. I would like to know when I select a part of the text, if this text is “wrapped” with html tags, and in the function it will be deleted.

For example, with this sentence:

The car is <strong> green </strong> and the boat is black

If I select “green” and press the button, I would like to check whether it is completed in “green” using <strong> (for this it is normal) and in the function tag <strong> tags without deletion containing “green”.

I tried to do this, but when I delete the child and recreate it, my new node is empty, and if I try to put the text directly in document.createTextNode , a new node will appear, but the <strong> tags remain.

 // Bouton CLICK $('input[type=button].btn_transform').click(function(){ var selObj = window.getSelection(); var parent=selObj.anchorNode.parentNode; if (parent.nodeName=='STRONG'){ parent.removeChild(selObj.anchorNode); var theText = document.createTextNode(selObj); parent.appendChild(theText); } }); 

I am not a specialist in manipulating the DOM. Could you help me solve this problem?

Thanks so much for your precious help.

+4
source share
3 answers

Mark this post for a selection method that selects information no matter which browser it is in:

Selecting text in an element (akin to mouse highlighting)

I think if you use the SelectText method, then it should work fine, not getSelection ()

Hope this helps.

+1
source

It should work the way you want by simply setting the parent outerHTML ( <strong>green</strong> ) to innerHTML ( green ) in it, for example:

 $('input[type=button].btn_transform').click(function(){ var selObj = window.getSelection(); var parent=selObj.anchorNode.parentNode; if (parent.nodeName=='STRONG'){ parent.outerHTML = parent.innerHTML; } }); 
0
source

using mostly jQuery ...

 $(document).ready(function () { $("#btn_transform").click(function () { var selectedText = getSelText(); var parentOf = $("strong:contains(" + selectedText + ")"); $(parentOf).each(function () { if (this.tagName == "STRONG" || this.tagName == "strong") { var theElement = $(this); var itsText = $(this).text(); $(this).after(itsText); $(this).remove(); } }); }); }); function getSelText(){ // your chosen 'get selection' method... { 

The only problem you may encounter is to select the text that appears more than once, so the function will match all instances of this text contained between the <strong> tags and delete them all.

I can give you some ideas, although I think. Rob

0
source

Source: https://habr.com/ru/post/1304464/


All Articles