Reputation: 914
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
Upvotes: 6
Views: 4097
Reputation: 1578
This is regex pattern to take all image tag:
var pattern = /\<img .+?\/\>/ig;
UPDATE: sample is here http://jsbin.com/oxafab/edit#source
Upvotes: 1
Reputation: 322462
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.
Upvotes: 5
Reputation: 46050
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>');
Upvotes: 1