Home > Enterprise >  How can I use JavaScript to find if an element has position fixed?
How can I use JavaScript to find if an element has position fixed?

Time:05-02

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?

CodePudding user response:

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

CodePudding user response:

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

CodePudding user response:

It works though... You should clarify your exact problem so that I can help you further.

  • Related