So i'm trying to change the margin of my h1
heading in the following snippet of code, using JavaScript for accuracy and because CSS does not support the auto
property for the h1
margin
. To do this, I am adding a margin using the document.
object. I would use more advanced JavaScript to divide the width of the window in half and position the h1
heading there, however if such a simple code like this:
document.getElementsByTagName("h1")[0].style.marginLeft = "500px";
doesn't work then what is the point? Can anyone explain to me why this does not work and give me a suitable resolve to the issue? Thanks in advance.
UPDATE
It seems that the code decides to work when it is called in a function but not when it left out on its own. Any help to why?
You have to put the 500px measurement in quotes like this:
document.getElementById("qwert").style.marginLeft = "500px";
If you explain your larger problem, it may be that this can be solved entirely with CSS too and not have to use JS for it.
Now, that you've entirely changed what you're asking in your question (which you are NOT supposed to do here), I'll try to address the new question you're asking.
If the code only works when called in a function, then you either have a syntax error or a timing error. My guess would be that when the code is not in a function, you are executing it too early before the DOM elements have been parsed and are present.