Skip to content Skip to sidebar Skip to footer

Add Width Attribute To Img In A String

lets say i have string something like x = '

Solution 1:

You can use the height property to set the value of the height attribute of an image. And width to set width.

Use for loop as shown below if you have multiple img tags in your string. If not you can simply use images[0] without for loop.

EDIT : If you want to change the string itself, just reassign the string as shown below

var string ="<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");
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;  // reassign the 'string' with new valueconsole.log(string);

Post a Comment for "Add Width Attribute To Img In A String"