开发者

Need Regular expression javascript to get all images

开发者 https://www.devze.com 2023-04-12 23:10 出处:网络
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.

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 开发者_如何学CJavascript


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.


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>');


This is regex pattern to take all image tag:

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

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

0

精彩评论

暂无评论...
验证码 换一张
取 消