How to replace a piece of HTML with another piece of HTML on a page? [duplicate]

你说的曾经没有我的故事 提交于 2019-12-25 04:15:58

问题


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.


回答1:


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.



来源:https://stackoverflow.com/questions/30440603/how-to-replace-a-piece-of-html-with-another-piece-of-html-on-a-page

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!