How to get width in javascript

Javascript document.querySelector() method with offsetWidth.

<div class="d"></div>

<button onclick="getWidth()">Get width</button>

<p>You are seeing 2px extra width because of border.</p>

<style>
.d {
    width: 300px;
    border: 1px solid #ccc;
    height: 200px;
    margin-bottom: 20px;
}
</style>

<script>
function getWidth() {
    let div = document.querySelector('.d');
    alert(div.offsetWidth);
}
</script>

Related Sourcecode

More Sourcecode

×
Google login
SignUp with Email
X