Reputation: 6675
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?
Upvotes: 3
Views: 675
Reputation: 1365
I am late to answer this question. to check an element if it is fixed. you can use window.getComputedStyle
to check all ancestors.
function isPositionFixed(element) {
let currentElement = element;
while (currentElement !== null && currentElement.nodeType === Node.ELEMENT_NODE) {
const style = window.getComputedStyle(currentElement);
if (style.position === 'fixed') {
return true;
}
currentElement = currentElement.parentElement;
}
return false; // No ancestor has position absolute
}
Upvotes: 0
Reputation: 645
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';
}
Upvotes: 2
Reputation: 326
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';
}
Upvotes: 2