Dom 节点操作,如何删除包裹我的选择的标签?
我试着向你解释我的“问题”。我想知道当我选择文本的一部分时,该文本是否被 html 标签“包裹”,并在功能中删除它们。
例如这句话:
汽车是绿色
,船是黑色
如果我选择“ green”并单击一个按钮,我想验证绿色是否被 包裹(因为没问题),并在函数中删除
未删除的标签包含“绿色”。
我尝试过这样做,但是当我删除子节点并重新创建一个时,我的新节点为空,如果我尝试直接将文本放入 document.createTextNode
中,我的新节点会出现,但 标签保留。
// 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);
}
});
我不是 DOM 操作专家。你能帮我解决这个问题吗?
非常感谢您的宝贵帮助。
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
查看这篇文章的选择方法,无论使用哪种浏览器都可以选择信息:
在元素中选择文本(类似于用鼠标突出显示)
我认为如果您使用 SelectText 方法,那么它应该可以正常工作,而不是 getSelection()
希望它有帮助。
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.
只需将父级的outerHTML(
green)设置为其innerHTML(
green
),它就应该按照您想要的方式工作,如下所示:It should work how you want it by just setting the parent's outerHTML (
<strong>green</strong>
) to it's innerHTML (green
), like this:主要使用 jQuery...
您可能遇到的唯一问题是,如果您选择多次出现的文本 - 因此该函数将匹配
标记之间包含的该文本的所有实例将它们全部删除。
我想可能会给你一些想法。
抢
using mostly jQuery...
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