0

I am creating an image object in JavaScript as

myImg = document.createElement('<img id=preview_image src="src/myImage.jpg" align="baseline" width="50%" height="80%"/>');

The image HTML will be obtained from database as in the given form. Now, how can I get the height and width with the units (i.e. 50% for width in this case)?

kashif
  • 1
  • 2
  • 2
    This will only work in IE8 and below. IE9 and other browsers don't support providing attributes in `document.createElement()`. You can only pass the element name. – detaylor Apr 27 '11 at 13:35
  • then what would be the better way to create an image element, with the above HTML? – kashif Apr 27 '11 at 13:46
  • 1
    If you were able to you would create the element using the tag name and then setting attributes via properties. You can create elements from JS libraries including jQuery or Prototype, check out [How do I create a new DOM element from an HTML string using built-in DOM methods or prototype](http://stackoverflow.com/questions/494143/how-do-i-create-a-new-dom-element-from-an-html-string-using-built-in-dom-methods) – detaylor Apr 27 '11 at 14:02
  • so, I'll be creating an `IMG` element and then parsing the HTML string to populate the respective `IMG` attributes, is there any better way? – kashif Apr 27 '11 at 15:07
  • The link shows another way, essentially creating a `div`, setting it's `innerHTML` and then using `childNodes` which will be the HTML content of the string. – detaylor Apr 27 '11 at 15:16

2 Answers2

3
var width = myImg.width,   // width = '50%'
    height = myImg.height; // height = '80%'

// or
width = myImg.getAttribute('width'),
height = myImg.getAttribute('height');
Matt Ball
  • 354,903
  • 100
  • 647
  • 710
  • for any image object you can find it using above method. – Kumar Apr 27 '11 at 13:32
  • i tried both even before posting the question, the only way to get the value is `myImg.attributes['width'].ie8_value` but this will make it IE8 specific, Can I have some way to do it for atleast some popular IEs (7,8 & 9)? – kashif Apr 27 '11 at 14:33
  • @kashif: `getAttribute('width')` correctly returns `'50%'` in IE9 and Chrome 10. I'm not set up to test any other versions of IE, sorry. http://jsfiddle.net/mattball/xHDL7/ – Matt Ball Apr 27 '11 at 14:43
0

As documented every DOMElement has a ClientHeight and ClientWidth property, those will have the values you need.

https://developer.mozilla.org/en/DOM/element

TJHeuvel
  • 12,403
  • 4
  • 37
  • 46