简体   繁体   中英

how to add class to an element in a html string in javascript?

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.

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

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

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