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")?

3
  • Check this answer: stackoverflow.com/a/11396681/7982963 Commented Oct 20, 2021 at 11:47
  • If you are simply trying to get an element's position with JavaScript, it's already been asked here: stackoverflow.com/questions/442404/… Commented Oct 20, 2021 at 11:51
  • 1
    @MoaazBhnas They are asking about the position CSS property value, "relative" in this example. Commented Oct 20, 2021 at 11:57

3 Answers 3

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;
Sign up to request clarification or add additional context in comments.

Comments

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'));
    });

Comments

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"

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.