1

I have a html string from backend API and I want to add class to all the image element in the html string, I was able to do it with jQuery but as jQuery doesn't work in server side rendering so I am looking for solutions in javascript.

here is the html string

let html="<p>here is a blog test<img src="https://bucket.s3.ap-south-1.amazonaws.com/83a5e290-8a8d-11ea-8466.jpg"></p>"

I want to add class to the image element

Any help or suggestions will be greatly appreciated.

ROOT
  • 11,363
  • 5
  • 30
  • 45
punit das
  • 119
  • 3
  • 9

2 Answers2

1

I think you can use `` backticks to form your content, for example:

let html = `<p>here is a blog test<img src="https://bucket.s3.ap-south-1.amazonaws.com/83a5e290-8a8d-11ea-8466.jpg" class=${className}></p>`
kyapwc
  • 322
  • 2
  • 4
  • 9
  • i am getting the html string from backend api and need to add the class dynamically with extracting the image tags first – punit das May 21 '20 at 07:04
  • Could you perhaps explain more about what you mean? I don't quite understand what you mean by "extracting the email tags first" – kyapwc May 21 '20 at 07:06
0

You can use DOMParser to achieve this, there is also a way to do it with str.replace but its not a clean way in opinion, here is a working example:

let html='<p>here is a blog test<img src="https://bucket.s3.ap-south-1.amazonaws.com/83a5e290-8a8d-11ea-8466.jpg"></p>'


parser = new DOMParser();
doc = parser.parseFromString(html, "text/html");

let images = doc.firstChild.getElementsByTagName('img');

for(let i =0; i<images.length; i++) {
  images[i].classList.add('img-element');
  console.log(images[i]);
}
ROOT
  • 11,363
  • 5
  • 30
  • 45
  • tried this but its throwing an error of DOMParser is not defined in node js server – punit das May 21 '20 at 07:34
  • @punitdas, didn't notice the SSR tag, I should have noticed it, DOMParser doesn't come with node, so you should use npm module for that also check if window.DOMParser is available or not, check this: https://stackoverflow.com/questions/11398419/trying-to-use-the-domparser-with-node-js/55668667 – ROOT May 21 '20 at 07:41