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
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>');
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With