Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

222
Vistas
How can I use JavaScript to find if an element has position fixed?

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?

about 4 years ago · Juan Pablo Isaza
2 Respuestas
Responde la pregunta

0

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';
}
about 4 years ago · Juan Pablo Isaza Denunciar

0

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';
}
about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda