简体   繁体   中英

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. Questions and Answers. Answers have been created using summernote and hence we're able to render raw HTML into the app. But to allow zooming of images, we need to replace all the occurrences of img tag in the answer content.

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

With

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

Using only pure 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> . 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.

<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:

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);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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