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)?

5
  • 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. Commented Apr 27, 2011 at 13:35
  • then what would be the better way to create an image element, with the above HTML? Commented Apr 27, 2011 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 Commented Apr 27, 2011 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? Commented Apr 27, 2011 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. Commented Apr 27, 2011 at 15:16

2 Answers 2

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

// or
width = myImg.getAttribute('width'),
height = myImg.getAttribute('height');
Sign up to request clarification or add additional context in comments.

3 Comments

for any image object you can find it using above method.
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: getAttribute('width') correctly returns '50%' in IE9 and Chrome 10. I'm not set up to test any other versions of IE, sorry. jsfiddle.net/mattball/xHDL7
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

1 Comment

clientHeight and clientWidth return pixel values, which is not what the OP wants.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.