I try to explain you my "problem". I would like to know when I select a part of text, if this text is “wrapped” by html tags, and in function delete them.
For example with this sentence :
The car is <strong>
green</strong>
, and the boat is black
If I select “green” and click on a button, I would like verify if green is wrapped by <strong>
(for that it’s ok), and in function delete <strong>
tags without delete containing “green”.
I have tried to do it, but when I remove child and recreate one, my new node is empty and if I try to put directly text in document.createTextNode
, my new node appears but the <strong>
tags stay.
// 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’m not a DOM manipulation specialist. Could you help me to solve this?
Thanks very much for your precious help.
Check out this post for a selection method which selects the information no matter which browser it is:
Selecting text in an element (akin to highlighting with your mouse)
I think if you make use of SelectText method then it should work fine instead of getSelection()
Hope it helps.
It should work how you want it by just setting the parent's outerHTML (<strong>green</strong>
) to it's innerHTML (green
), like this:
$('input[type=button].btn_transform').click(function(){
var selObj = window.getSelection();
var parent=selObj.anchorNode.parentNode;
if (parent.nodeName=='STRONG'){
parent.outerHTML = parent.innerHTML;
}
});
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 might have is if you select text that appears more than once - therefore the function will match all instances of this text being contained in between <strong>
tags and delete them all.
Might give you some ideas though I guess. Rob
精彩评论