-1

I have a string like this.

x = '<div class="sample">
         <img src="http://www.example.com/i/java.png"> 
     </div>
     <div class="sample_another">
         <img src="/i/somedir/python.png"> 
    </div>'

I want to convert to this

x = '<div class="sample">
         <img src="http://www.example.com/i/java.png" height="200px" width="100px"> 
     </div>
     <div class="sample_another">
         <img src="/i/somedir/python.png" width="150px" height="150px"> 
    </div>'

input string will be a html doc. for all the images in the doc, i want to add the height and width property. and to get the height and width property i have to use something like this

var img = new Image();
img.onload = function() {
  alert(this.width + 'x' + this.height);
}
img.src = 'http://www.example.com/intl/logo.gif';

p.s. i tried using this solution but the problem i face is that the string might have the script tag and DOM parses it as a closing script tag. I cant find much for regex either. So is there any other way to obtain this result ? Thanks.

Pujan
  • 69
  • 1
  • 12

1 Answers1

1

If you can remove scripts than go with this code:

<script 
 src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js">
</script>
  var string ="<script type"text/javascript"></script><img alt='' 
 src='http://api.com/images/UID' /><br/>Some plain text<br/><a 
  href='http://www.google.com'>http://www.google.com</a>";

var elem= document.createElement("div");

$(string).find('script').remove();

elem.innerHTML = string;

    var images = elem.getElementsByTagName("img");

   for(i=0; i<images.length; i++){
      images[i].width = "150";
     images[i].height = "250";
   }

   string = elem.innerHTML; 

Problem you are facing with is that it turns out that HTML5 does not allow script tags to be dynamically added using the innerHTML property. So you will need to add them dynamically on some other way.

This is some code that might help you:

var my_awesome_script = document.createElement('script');
my_awesome_script.setAttribute('src','http://example.com/site.js');
document.head.appendChild(my_awesome_script);
Vlado Pandžić
  • 4,879
  • 8
  • 44
  • 75