3

Using JavaScript I need to find an element that has position fixed and set its top attribute to 60px.

const myDiv = document.querySelector('.my-div')
if(myDiv && myDiv.style.position == 'fixed') {
    myDiv.style.top = '60px';
}

But it doesn't work. What is wrong in my code?

user1941537
  • 6,097
  • 14
  • 52
  • 99
  • sorry that was just a type as I created the question here. – user1941537 May 01 '22 at 12:08
  • what is `doesn't work` mean? you can not find the div? – hoangdv May 01 '22 at 12:11
  • Is the code being run *after* the document has loaded, as it needs to be? – Andrew Morton May 01 '22 at 12:18
  • Now I know why it's not working. The element's position gets changed after it's out of the viewport. So when the document is ready, the position is not fixed yet. I need to check the element after it's out of viewport or maybe on scroll. Which solution would be better? – user1941537 May 01 '22 at 12:28
  • 1
    @user1941537 That depends on the context, and we have absolutely none of it. Could you elaborate a bit more? – HerrAlvé May 01 '22 at 12:31
  • my-div element has position absolute. When you scroll the page, as soon as my-div is out of the view port its position changes to fixed and top: 0. Here I need to change the value 0 for top to 100px. – user1941537 May 01 '22 at 12:34

2 Answers2

2

The element.style.prop deals with the inline styles of an element, only. It is not affected by the changing of embedded or external styles (more information here). Thus, you cannot use it to get the value of a non-inline property.

Therefore, you need to use this :-

const myDiv = document.querySelector('.my-div');

if (myDiv && window.getComputedStyle(myDiv).getPropertyValue('position') == 'fixed') {
    myDiv.style.top = '60px';
}

Refer them from here: getComputedStyle and getPropertyValue.

Or even more simply, you could simply use the . or the [] notation to get the values. You can check out the differences here.

const myDiv = document.querySelector('.my-div');

if (myDiv && window.getComputedStyle(myDiv).position == 'fixed') {
    myDiv.style.top = '60px';
}
HerrAlvé
  • 587
  • 3
  • 17
2

You can use window.getComputedStyle().

It will return an object with all styles, even if not explicitly defined by you, unlike the style property which only holds the style values which you explicitly set.

For your code, it would look like this:

const myDiv = document.querySelector('.my-div')
if (!myDiv) return; // Early return guard to avoid calling getComputedStyle with null
const style = window.getComputedStyle(myDiv)

if (style.position === 'fixed') {
    myDiv.style.top = '60px';
}
Sam McElligott
  • 306
  • 1
  • 4