I produced some very basic code and wonder how it’s possible that one part of the function’s body works, while the other one doesn’t. Here is my code:
<!DOCTYPE html>
<html>
<body>
<div id="id1">My Heading 1</div>
<button type="button" onclick="changecolor()">Click Me!</button>
<script>
function changecolor() {
var domElement = document.getElementById('id1');
domElement.style.top = 100;
domElement.style.color = 'red';
}
</script>
</body>
</html>
Changing the color works, but changing the position does not. Why is that?
3
Answers
By default, HTML elements have
position: 'static'
which means thattop
has no effect whatsoever (documentation):Change the
position
(e.g.domElement.style.position = 'absolute'
) as per your needsAdditionaly, the
top
property needs to be a string and needs to have a unit, as per its syntaxstyle.top is just expecting a string, not a number.
In addition, you should ensure that style.position is set appropriately. The below modified code will achieve your desired result
Elements with
position: static
(the default) do not honour properties liketop
; use e.g. valuerelative
.Also, you are using a unit-less length, which I think is invalid.