2

For example I have this <div> with the following CSS:

.some-div{
   position: relative;
   top: 50px;
}
<div class="some-div">
   <p>Some content</p>
</div>

How do I get the CSS property position of the element with JavaScript (which in this example should result in the string "relative")?

CherryDT
  • 25,571
  • 5
  • 49
  • 74
Luuk
  • 641
  • 4
  • 12
  • Check this answer: https://stackoverflow.com/a/11396681/7982963 – Moaaz Bhnas Oct 20 '21 at 11:47
  • If you are simply trying to get an element's position with JavaScript, it's already been asked here: https://stackoverflow.com/questions/442404/retrieve-the-position-x-y-of-an-html-element – Moaaz Bhnas Oct 20 '21 at 11:51
  • 1
    @MoaazBhnas They are asking about the `position` CSS property value, `"relative"` in this example. – CherryDT Oct 20 '21 at 11:57

3 Answers3

5

Window.getComputedStyle()

The Window.getComputedStyle() method returns an object containing the values of all CSS properties of an element, after applying active stylesheets and resolving any basic computation those values may contain

const element = document.getElementById('your_element_id');
const computedStyles = getComputedStyle(element);
const position = computedStyles.position;
Steve
  • 93
  • 1
  • 9
1

Assuming your "class" has only one element:

HTML

<div class="some-div"">
  <p>Some text</p>
</div>

JAVASCRIPT

    let someDiv = document.getElementsByClassName('some-div')[0];
    someDiv.addEventListener('click', () => {
        console.log(this.getComputedStyle(someDiv).getPropertyValue('position'));
    });
0
    var element = document.querySelector('.some-div');
    var style = window.getComputedStyle(element);
    var pos = style.position;
    console.log(pos);

Try this. The Console output must be: "relative"

Adrian Tocu
  • 189
  • 1
  • 12