JavaScript Answers

How to get the position of a div/span tag with JavaScript?

Spread the love

To get the position of a <div> or <span> element with JavaScript, you can use the getBoundingClientRect() method.

This method returns a DOMRect object containing the size and position of the element relative to the viewport.

To do this, we write:

<!DOCTYPE html>
<html lang="en">
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Get Element Position</title>
    <div id="myDiv" style="width: 100px; height: 100px; background-color: red;"></div>
    <span id="mySpan" style="display: inline-block; width: 50px; height: 50px; background-color: blue;"></span>

        // Get the div element
        var div = document.getElementById('myDiv');
        // Get the span element
        var span = document.getElementById('mySpan');

        // Get the position of the div
        var divPosition = div.getBoundingClientRect();
        console.log('Div position:', divPosition);

        // Get the position of the span
        var spanPosition = span.getBoundingClientRect();
        console.log('Span position:', spanPosition);

In this example, we have a <div> and a <span> element with some inline styles to give them dimensions and background colors.

We use document.getElementById() to get references to these elements.

Then we call getBoundingClientRect() on each element to get their position relative to the viewport.

The returned DOMRect object contains properties like top, left, right, bottom, width, and height, which represent the position and dimensions of the element.

You can use these properties to determine the exact position of the elements on the page and perform further calculations as needed.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *