如何用页面上的另一片HTML代替一段HTML? [英] How to replace a piece of HTML with another piece of HTML on a page?

查看:202
本文介绍了如何用页面上的另一片HTML代替一段HTML?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在做一个简单的浏览器扩展,这应该是用于链接添加在一个页面上。
这个扩展应该引用法律来查找文本,并把它们包含在相应页面的链接和法律文本中。

例如,参考 code>某些法律第一章在文本中 Some Law 这样的链接 - < a href =http://link-to-the-law.text> Some Law< / a>

$ b

用户通过这种方式与扩展进行交互:


  1. 在页面上选择一些文本(它可以包含许多DOM元素)
  2. 通过点击一个右键菜单按钮来触发文本打包

  3. 我们的服务器将执行所选文本

  4. 返回包含链接的法律引用的文本
  5. 所选文本被替换为返回的文本
  6. li>

现在我坚持了第5步。我有一个 Selection对象和一个原始的重新通过包装引用来接收HTML。

是否有可能(以及如何)将接收到的文本替换为选定的文本(实际上是一堆DOM元素)?
也许你遇到过一些扩展/库/等行为相似?或者你可能知道一个更好的方法来做这样的替换?如果是这样,请让我知道。

解决方案

我不太清楚你在问什么,但是从我理解你想要的用其他DOM元素替换DOM元素。查看 innerHTML 和/或 createElement


I'm making a simple browser extension which is supposed to be used for links addition on a page. The extension should to find text occurrences with references to laws and wrap them in links to corresponding pages with texts of laws.

For example, the reference "chapter 1 of Some Law" in a text "The topic covered in the chapter 1 of Some Law" should be wrapped with link like this - "The topic covered in <a href="http://link-to-the-law.text">chapter 1 of Some Law</a>"

A user interacts with the extension this way:

  1. selects some text on a page (it can include many DOM elements)
  2. triggers text wrapping by clicking a right-click menu button
  3. CORS with the selected text are performed to our server
  4. a text with law references wrapped in links is returned
  5. the selected text is replaced with the returned text

Now I've stuck with the step 5. I have a Selection object and a raw received HTML with wrapped references.

Is it possible (and how if so) to replace a selected text (which actually is a bunch of DOM elements) with a received text? May be you have encountered some extensions/libraries/etc which acts similarily? Or may be you know a better way to do such a replacement? If so please let me know.

解决方案

I'm not quite sure what you are asking, but from what I understand you want to replace DOM elements with other DOM elements. Look into innerHTML and/or createElement.

这篇关于如何用页面上的另一片HTML代替一段HTML?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆