gpt4 book ai didi

javascript - 如果 id 匹配则删除标签但保留文本

转载 作者:行者123 更新时间:2023-11-30 10:38:24 24 4
gpt4 key购买 nike

我有一个荧光笔功能,可以将匹配的单词格式化为带有黄色 bg-color 的 anchor ,我需要一个函数来删除 anchor 元素以进行下一次搜索。

匹配词的标记,第一个词如下所示:

<a id="searchword1" class="searchword" style="background-color: yellow; text-decoration: none; color: black;">my text</a>

我需要删除 anchor 但将我的文本留在那里。我不想干扰文档中的其他 anchor 。我需要用纯 Javascript(没有 jQuery)来做这件事。

  • 附加要求:删除标签后不要创建新行,保持原样。

感谢 enhzflep,直到现在的代码:

for (z=0;z<szam;z++){
var removal = parent.frames['pagina'].document.getElementById("searchword"+z);
var highlightedText = removal.innerHTML.toLowerCase;
removeh(removal,highlightedText,doc);
}


function removeh(node,high,doc) {
doc = typeof(doc) != 'undefined' ? doc : document;
if (node.hasChildNodes) {
var hi_cn;
for (hi_cn=0;hi_cn<node.childNodes.length;hi_cn++) {
removeh(node.childNodes[hi_cn],high,doc);
}
}
//1. Get element containing text
if (node.nodeType == 3) {
tempnode = node.nodeValue.toLowerCase();
if (tempnode.indexOf(high) != -1) {
nv = node.nodeValue;
nv = node.nodeValue;
ni = tempnode.indexOf(high);
//2. Get the text it contains
before = doc.createTextNode(nv.substr(0,ni));
dochighVal = nv.substr(ni,high.length);
after = doc.createTextNode(nv.substr(ni+high.length));
//3. Get the highlighted element's parent
var daddy = node.parentNode;
//4. Create a text node:
var newNode = document.createTextNode(dochighVal);
//5. Insert it into the document before the link
daddy.insertBefore(before, node);
daddy.insertBefore(newNode, node);
daddy.insertBefore(after, node);
//6. Remove the link element
daddy.removeChild(node);
}
}
}

其中 num 是匹配词的数量。

由于某种原因,这不起作用,请帮忙,我也会接受解决这个小问题的答案。

有两个答案的方法是正确的,但它仍然有问题,因为它用新行分隔结果文本。这使得荧光笔功能将“我的话”作为单独的临时节点值,并且无法突出显示/my.word/的匹配项。

最佳答案

如果我没理解错的话,你想把这个:

<a id="searchword1" class="searchword" style="background-color: yellow; text-decoration: none; color: black;">my text</a>

进入这个:

my text

如果是这样的话,那就很简单了。

就目前而言,您似乎在要求您显示的元素的子元素(该元素没有任何子元素,除了文本节点。我希望您的脚本在第 2 行被处理 - 当它试图得到一个不存在的 child )

 //1. Get element containing text

var element = document.getElementById('searchWord1');


//2. Get the text it contains

var highlightedText = element.innerHTML;


//3. Get the highlighted element's parent

var parent = element.parentNode;


//4. Create a text node:

var newNode = document.createTextNode(highlightedText);


//5. Insert it into the document before the link

parent.insertBefore(newNode, element);


//6. Remove the link element

parent.removeChild(element);

关于javascript - 如果 id 匹配则删除标签但保留文本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12709293/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com