开发者

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

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜