简体   繁体   English

如何使用纯JavaScript用img标签替换HTML字符串

[英]How to replace a HTML String with img tags using pure javascript

We have some content coming from the backend api into an Ionic 2 App. 我们有一些内容从后端api进入Ionic 2 App。 Questions and Answers. 问题与解答。 Answers have been created using summernote and hence we're able to render raw HTML into the app. 答案是使用summernote创建的,因此我们能够将原始HTML呈现到应用程序中。 But to allow zooming of images, we need to replace all the occurrences of img tag in the answer content. 但是为了允许图像缩放,我们需要替换答案内容中所有出现的img标签。

<img src="pathofimg" attribute1="att1" ...>

With

<ion-scroll scrollX="true" scrollY="true">
  <img src="pathofimg" attribute1="att1" ...>
</ion-scroll>

Using only pure javascript . 仅使用纯javascript

I know regex is the good approach but open for suggestions. 我知道正则表达式是一种很好的方法,但是愿意接受建议。

As an example, this wraps each child element <span> into a wrapper element <p> . 例如,这将每个子元素<span>包装到包装器元素<p> Simply replace the element names and selectors with your own. 只需用您自己的元素名称和选择器替换即可。 You may want to use document.querySelector() if your parent element isn't easy to select. 如果您的父元素不容易选择,则可能要使用document.querySelector()

<div>
  <span>0</span>
  <span>1</span>
  <span>2</span>
  <span>3</span>
  <span>4</span>
</div>

<script>
    var commonParentElement = document.getElementsByTagName('div')[0];
    var imgs = commonParentElement.getElementsByTagName('span');

    for (var i=0; i<imgs.length; i++) {
      var wrap = document.createElement('p');
      wrap.setAttribute('style', 'font-weight:bold;');
      wrap.appendChild(imgs[i]);
      commonParentElement.insertBefore(wrap, imgs[i]);
    }
</script>

Here in a plunker 在这里

As you added only javascript tag to your question, here is solution using "native" document.getElementsByTagName and element.replaceChild methods: 当您仅向问题添加javascript标记时,以下是使用“本机” document.getElementsByTagNameelement.replaceChild方法的解决方案:

var images = document.getElementsByTagName('img'),
    len = images.length, img, ion, parent;

while (len--) {
    ion = document.createElement("ion-scroll");
    ion.setAttribute("scrollX", "true");
    ion.setAttribute("scrollY", "true");

    img = images[len];
    parent = img.parentNode;
    ion.innerHTML = img.outerHTML;
    parent.replaceChild(ion, img);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM