Jake
Jake

Reputation: 26117

Detect and adjust width and height of images in dynamic HTML

I have some HTML that comes from a REST API. In that, I have a lot of tags that may or may not have a width and height property set. The units don't come in "px", but just as a number.

<img class="embedded-image" src="http://example.com/img.svg" height="150" 
width="200">

<img class="embedded-image" src="http://example.com/img.svg" height="150">

<img class="embedded-image" src="http://example.com/img.svg" width="200">

<img class="embedded-image" src="http://example.com/img.svg">

Using CSS or JavaScript, I would like target these "img" tags and apply width property with px if it's set and set the height property if it's set. If none of them are set, we just leave as is.

Upvotes: 0

Views: 61

Answers (1)

imvain2
imvain2

Reputation: 15857

Assuming you have already added them to the DOM, you can loop through and just see if the width and height exist.

var _imgs = document.querySelectorAll(".embedded-image");
_imgs.forEach(function(el){
  if(el.getAttribute("height") != null){
    el.style.height = el.getAttribute("height") + "px";
  }
  
  if(el.getAttribute("width") != null){
    el.style.width = el.getAttribute("width") + "px";
  }
});
<img class="embedded-image" src="http://example.com/img.svg" height="150" 
width="200">

<img class="embedded-image" src="http://example.com/img.svg" height="150">

<img class="embedded-image" src="http://example.com/img.svg" width="200">

<img class="embedded-image" src="http://example.com/img.svg">

Upvotes: 1

Related Questions