Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Need Regular expression javascript to get all images

I have string that contains html . The html has several img tags in it . I want to find all the img tags and have some kind of collection so that i can replace them with my code.

Does anybody has any idea.

I want it in Javascript

like image 526
Chief Avatar asked Oct 13 '11 12:10

Chief


2 Answers

var html_str = '...some images and other markup...';

var temp = document.createElement( 'div' );
temp.innerHTML = html_str;

var images = temp.getElementsByTagName( 'img' );

...then loop over the images...

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

What you actually need to do may change how your loop runs, but the above just adds a class, so it is just a normal for loop.

Note that at this point you're dealing with DOM elements, not markup. These elements can be added directly to the DOM.

like image 141
user113716 Avatar answered Sep 27 '22 23:09

user113716


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 images you would do:

var html = '<div><img src="bla" /></div>';
$(html).find('img').replaceWith('<div>Image was here</div>');
like image 34
Petah Avatar answered Sep 27 '22 21:09

Petah