How to get the image size (height & width) using JavaScript ?
For getting size of an image (height and width), Element.clientHeight and Element.clientWidth properties is used.
- Element.clientHeight: We can access the inner height of an element with this property. This height include the padding but not the margin and border.
- Element.clientWidth: We can access the inner width of an element with this property. This width include the padding but not the margin and border.
Note: Here Element is image, So image.clientHeight and image.clientWidth will be used respectively for getting height and width of the image.
Example: Getting image size.
<!DOCTYPE html> < html lang = "en" > < head > < meta charset = "UTF-8" > < title > getting-height-width-image-using-javascript </ title > < style > h1 { text-align: center; letter-spacing: 1px; } img, button { display: block; margin: 0 auto; } button { font-size: large; } </ style > </ head > < body > < h1 > Getting height and width of an image </ h1 > < br > < br > < img src = "https://media.w3wiki.net/wp-content/uploads/w3wiki-20.png" alt = "logo-w3wiki" id = "image" > < button type = "submit" onclick = "myFunc()" > Get height and width </ button > < div style = "background-color: lightgray" > < div id = "height" > </ div > < div id = "width" > </ div > </ div > </ body > < script > function myFunc() { let image = document.getElementById('image'); let height = document.getElementById('height'); var width = document.getElementById('width'); height.innerHTML += '< h1 >height of image is :' + image.clientHeight + 'px </ h1 >'; width.innerHTML += '< h1 >width of image is :' + image.clientWidth + 'px </ h1 >'; } </ script > </ html > |
Output:
After clicking on the button:
After clicking on the button:
Contact Us