Need javascript regex to get all images

I have a line containing html. There are several img tags in html. I want to find all the img tags and have some collection so that I can replace them with my code.

Does anyone have any ideas.

I want it in javascript

+6
source share
3 answers
var html_str = '...some images and other markup...'; var temp = document.createElement( 'div' ); temp.innerHTML = html_str; var images = temp.getElementsByTagName( 'img' ); 

... then scroll through the images ...

 for( var i = 0; i < images.length; i++ ) { images[ i ].className = "my_class"; } 

What you really need to do can change how your loop works, but the above just adds a class, so this is a regular for loop.

Note that at the moment you are dealing with DOM elements, not markup. These elements can be added directly to the DOM.

+4
source

If you used jQuery, you could do something like:

 var html = '<div><img src="bla" /></div>'; $(html).find('img'); 

If you want to replace all the images you would make:

 var html = '<div><img src="bla" /></div>'; $(html).find('img').replaceWith('<div>Image was here</div>'); 
+1
source

This is a regex pattern to take all image tags:

 var pattern = /\<img .+?\/\>/ig; 

UPDATE : sample is here http://jsbin.com/oxafab/edit#source

+1
source

Source: https://habr.com/ru/post/899217/


All Articles