admin管理员组文章数量:1355117
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
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
Share Improve this question edited Oct 13, 2011 at 12:29 Chief asked Oct 13, 2011 at 12:07 ChiefChief 9141 gold badge9 silver badges26 bronze badges 5- 3 Regex is not the tool for this. jQuery would be able to do it out of the box - any chance of using that? – Pekka Commented Oct 13, 2011 at 12:10
- if i dont get collection then can i replace all of them with my predefined code – Chief Commented Oct 13, 2011 at 12:13
- Yup, that is possible as well. – Pekka Commented Oct 13, 2011 at 12:14
-
What do you mean by
collection
– Petah Commented Oct 13, 2011 at 12:14 - a collection means list or possibly all the img ones in a array – Chief Commented Oct 13, 2011 at 12:17
3 Answers
Reset to default 5var 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./oxafab/edit#source
本文标签: regexNeed Regular expression javascript to get all imagesStack Overflow
版权声明:本文标题:regex - Need Regular expression javascript to get all images - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1744034017a2579430.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论