The height property of an image element lets JavaScript read or change the height at which the image is rendered.
const height = document.getElementById('i1').height;
document.getElementById('i1').height = 100;
const height = document.getElementById('i1').height;
document.getElementById('i1').height = 100;Changing only one dimension may change the rendered aspect ratio depending on how the other dimension is constrained. For layout, responsive CSS is often preferable.
Demo changing height and width
<!doctype html>
<html lang="en">
<head><meta charset="utf-8"><title>Change image height with JavaScript</title></head>
<body>
<button type="button" id="expand">Expand</button>
<button type="button" id="compress">Compress</button>
<img src="images/help.jpg" id="i1" alt="Help illustration">
<script>
const image = document.getElementById('i1');
const expand = document.getElementById('expand');
const compress = document.getElementById('compress');
function resizeHeight(direction) {
let height = image.height;
if (direction === 'up' && height < 300) height *= 2;
if (direction === 'down' && height > 5) height = Math.max(5, Math.round(height / 2));
image.height = height;
}
expand.addEventListener('click', () => resizeHeight('up'));
compress.addEventListener('click', () => resizeHeight('down'));
</script>
</body>
</html>
Managing Width of Image Image Object
Author & Instructor at plus2net
I write and maintain practical tutorials on Python, PHP, SQL, JavaScript, HTML, jQuery, and web development at plus2net. The tutorials focus on clear explanations, working examples, and code that readers can test and adapt while learning.