Can not get attributes from internal style-sheet with document.querySelector... or document.getElementById

StackOverflow https://stackoverflow.com/questions/21781226

  •  11-10-2022
  •  | 
  •  

Pregunta

Maybe i'm crazy or tired. But I do not understand why I suddently can't retrieve my element-styles from the internal style-sheet. But it works if I make the style inline. A simple code-example:

<!DOCTYPE html>
<html>
<head>
    <title></title>
    <style>
        #box_1  {padding:1em;width:25%;background-color:blue;color:red;font-size:2em;font-weight:bolder}
        #test_1 {position:absolute;bottom:1em;right:1em;font-size:2em;}
    </style>
</head>
<body>
<div id="box_1" >
    BOX 1
</div>
<button id="test_1" type="button" onclick="test_1()">Alert font-color<br/> from box 1</button>
</body>
<script>
    function test_1()
    {
        var str=document.querySelector("#box_1").style.color;
        alert(str);
    }
</script>
</html>
¿Fue útil?

Solución

If you want to access the effective style of an element (including the globally defined CSS), use getComputedStyle():

function test_1() {
  var str=window.getComputedStyle( document.querySelector("#box_1") )
                .getPropertyValue ( 'color' );
  alert(str);
}

The style property itself, just refers to the elements style attribute and the styles you set by using JavaScript. See the respective MDN documentation for details.

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top