Home > database >  Get CSS position property of element with JavaScript
Get CSS position property of element with JavaScript

Time:10-21

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

CodePudding user response:

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('element_id');
const computedStyles = getComputedStyles(element);
const position = computedStyles.position;

CodePudding user response:

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

CodePudding user response:

    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"

  • Related